stay ASP.NET Methods and steps of accessing httpcontext in core5.0

Time:2020-12-10

ASP.NET Core applications access httpcontext through the ihttpcontextaccessor interface and its default implementation httpcontextaccessor. Ihttpcontextaccessor is only necessary if you need to access httpcontext within a service.

Using httpcontext through razor pages

Razor pages pagemodel exposes the httpcontext property:


public class AboutModel : PageModel
{
  public string Message { get; set; }


  public void OnGet()
  {
    Message = HttpContext.Request.PathBase;
  }
}

Using httpcontext through the razor view

The razor view uses the RazorPage.Context Property directly exposes httpcontext. The following example uses Windows authentication to retrieve the current user name in an intranet application:


@{
  var username = Context.User.Identity.Name;
  
  ...
}

Using httpcontext through the controller

Controller disclosure ControllerBase.HttpContext Properties:


public class HomeController : Controller
{
  public IActionResult About()
  {
    var pathBase = HttpContext.Request.PathBase;


    ...


    return View();
  }
}

Using httpcontext through Middleware

When using custom middleware components, httpcontext is passed to the invoke or invokeasync method, which can be accessed after middleware configuration


public class MyCustomMiddleware
{
  public Task InvokeAsync(HttpContext context)
  {
    ...
  }
}

Using httpcontext through custom components

For other frameworks and custom components that need to access httpcontext, it is recommended to use the built-in dependency injection container to register dependencies. The dependency injection container provides an ihttpcontextaccessor for any class to declare it as a dependency in its own constructor:


public void ConfigureServices(IServiceCollection services)
{
   services.AddControllersWithViews();
   services.AddHttpContextAccessor();
   services.AddTransient<IUserRepository, UserRepository>();
}

In the following example:

  • The user repository declares its dependency on ihttpcontextaccessor.
  • Dependency injection occurs when the dependency injection container resolves the dependency chain and creates a userrepository instance.

public class UserRepository : IUserRepository
{
  private readonly IHttpContextAccessor _httpContextAccessor;


  public UserRepository(IHttpContextAccessor httpContextAccessor)
  {
    _httpContextAccessor = httpContextAccessor;
  }


  public void LogCurrentUser()
  {
    var username = _httpContextAccessor.HttpContext.User.Identity.Name;
    service.LogAccessRequest(username);
  }
}

Accessing httpcontext from background thread

Httpcontext is not thread safe. Reading or writing properties of httpcontext outside of processing the request may result in a nullreferenceexception.

To perform background work safely using httpcontext data:

  • Copy the required data during request processing.
  • Pass the copied data to the background task.

To avoid unsafe code, do not pass httpcontext to methods that perform background work. It’s about passing the data you need. In the following example, sendemail core is called to start sending e-mail. Pass the correlationid to sendemail core instead of httpcontext. Code execution does not wait for sendemail core to complete:


public class EmailController : Controller
{
  public IActionResult SendEmail(string email)
  {
    var correlationId = HttpContext.Request.Headers["x-correlation-id"].ToString();


    _ = SendEmailCore(correlationId);


    return View();
  }


  private async Task SendEmailCore(string correlationId)
  {
    ...
  }
}

This article is about ASP.NET This is described in the article on accessing httpcontext in core5.0 ASP.NET To access httpcontext, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!