How to get the current Windows user with ASP.NET Core RC2 MVC6 and IIS7

前端 未结 4 1313
难免孤独
难免孤独 2021-01-17 10:48

I have an intranet site built in MVC6 using ASP.NET Core RC2. I want to get the Windows username of the person accessing the intranet site.

So if Jim goes to the in

4条回答
  •  北海茫月
    2021-01-17 11:23

    Might help someone who are still looking for. Per documentation from MS https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-2.2 , add the HttpContextAccessor in ConfigureServices method (startup.cs) Pass this httpcontextaccessor into the controller and access the logged in user.

    I followed this and I was able to get the logged in Windows Authenticated user even after deploying the core website to IIS.

    Here are the code snippets

    In Startup.cs (under ConfigureServices method) add the line

    services.AddHttpContextAccessor();
    

    Then in your controller file, add following piece of necessary code lines. The code below is a sample.

    public class YourController : Controller
    {
      private readonly IHttpContextAccessor _httpContextAccessor;
      private readonly string _user;
      public YourController(IHttpContextAccessor httpContextAccessor)
      {
        _httpContextAccessor = httpContextAccessor;
        _user = _httpContextAccessor.HttpContext.User.Identity.Name;
      }
    }
    

提交回复
热议问题