13 July 2022

How to enable windows authentication .net core project

 Go to "launchSettings.json" file as below image:

Then changes below two things in "launchSettings.json" file 

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:26887",
      "sslPort": 0
    }
  }
}

How to Get the Current User in ASP.NET Core

 Create new Controller and add below code:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Dotnet_Core_MVC.Controllers
{
    public class ExpHttpContextAccessorController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor = new HttpContextAccessor();
        public IActionResult Index()
        {
            string userName = _httpContextAccessor.HttpContext.User.Identity.Name;
            ViewBag.userName = userName;
            return View();
        }
    }
}

Go to View and add below code:

 <b>Welcome:@ViewBag.userName</b>

Update ConfigureServices() in Startup.cs as below:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddHttpContextAccessor(); 
        }

How to use ViewBag inside of Filters of Asp.net Core

 Create ViewBag in Action Filter as below: 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
namespace Dotnet_Core_MVC.CustomActionFilters
{
    public class CustomActionFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Controller is Controller controller1)
            {
                controller1.ViewBag.MyName = "Adi";
            }
        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
           
        }
    }
}

Use ViewBag in your View Pages as Below:

 <b>Welcome:@ViewBag.MyName</b>