Home > OS >  Blazor throwing error when using HttpContext
Blazor throwing error when using HttpContext

Time:11-11

I want to get current windows user name when user opens the website. My application uses Blazor server-side. To get current username, I added:

  1. In startup.cs:
    services.AddHttpContextAccessor(); (under ConfigureServices)
  2. In razor page:
    @inject IHttpContextAccessor httpContextAccessor
  3. In razor page method:
    string userName = httpContextAccessor.HttpContext.User.Identity.Name;

When I execute the code, the application throws an exception:

"An error has occurred. This application may no longer respond until reloaded."

I get this error only when I deploy on IIS. On local machine it works well.

CodePudding user response:

If you were to change that string from

string userName = httpContextAccessor.HttpContext.User.Identity.Name

to

string userName = httpContextAccessor?.HttpContext?.User?.Identity?.Name??"Anonymous"

then it would probably work.

It's because your IIS settings are allowing anonymous access and so your Identity object is null.

You should check for the inner exceptions behind the application crash but that will be your issue. You need to prevent anonymous access on IIS to get the Windows authentication passed through.

To manage IIS refer here https://stackoverflow.com/a/5458963/12285843

CodePudding user response:

HttpContext is not available in Blazor Server App where the front end (browser) and the back end ( server) communicate via SignalR. The HttpContext is a feature of the HTTP protocol not the SignalR protocal.

What to do ? Look for my answers in the the results for the Google search: "enet stackoverflow blazor httpcontext"

  • Related