RKh
RKh

Reputation: 14161

Blazor throwing error when using HttpContext

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.

Upvotes: 2

Views: 2100

Answers (3)

DaBeSoft
DaBeSoft

Reputation: 79

The Microsoft Docs for Blazor state:

IHttpContextAccessor generally should be avoided with interactive rendering because a valid HttpContext isn't always available.

Use AuthenticationStateProvider instead as described here.

In your case that would be:

@inject AuthenticationStateProvider authenticationStateProvider
instead of
@inject IHttpContextAccessor httpContextAccessor

and

var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
string userName = authState.User.Identity.Name;

instead of
string userName = httpContextAccessor.HttpContext.User.Identity.Name;

Upvotes: 0

Eduardo Heidrich
Eduardo Heidrich

Reputation: 207

I had a similar issue trying to access HttpContext for user information using Blazor. I found this here which was a life saver. HttpContext is NULL when running web app in IIS All I had to do to solve the problem was to enable WebSockets in IIS.

Here are the steps: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1#iisiis-express-support

Upvotes: 1

Frank
Frank

Reputation: 1080

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

Upvotes: 0

Related Questions