Home > Blockchain >  IHttpContextAccessor scope
IHttpContextAccessor scope

Time:03-04

I have IHttpContextAccessor injected in a controller. I am reading user name from IHttpContextAccessor and returning it back to the UI.

My question is is very basic. I need to understand how this will work when multiple users will connect and request User Name.

I just want to make sure that the user names will be returned only for the corresponding user.

I don't want to save the user name in session variable after returned to the client. Whenever is needed, I will request a call and get it from the context.

Is this approach valid?

private IHttpContextAccessor ctx
public EmployeeController(IHttpContextAccessor context)
{
  ctx=context;
}

public string GetEmployeeName()
{
   return ctx.HttpContext.User.UserName;
}

CodePudding user response:

The HttpContextAccessor will be registered as the Singleton service when you called AddHttpContextAccessor.

According to the source codes, you could find the HttpContextAccessor will check the _httpContextCurrent value when it call get and set method. It will auto set the _httpContextCurrent.Value when the new request come to the application.

  • Related