Method steps for accessing HttpContext in ASP. NET Core 5.0

  • 2021-11-14 05:26:22
  • OfStack

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 the service.

Use HttpContext through Razor Pages

Razor Pages PageModel exposes HttpContext properties:


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


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

Using HttpContext through Razor view

The Razor view exposes HttpContext directly through the RazorPage. Context property on the view. 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

The controller exposes the 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 methods, which are accessible after the middleware is configured:


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

Using HttpContext through custom components

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


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

In the following example:

UserRepository declares its dependence on IHttpContextAccessor. Dependencies are injected when the dependency injection container resolves the dependency chain and creates an 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);
  }
}

Access HttpContext from a background thread

HttpContext is not thread safe. Reading or writing HttpContext properties outside of processing the request may result in NullReferenceException.

To safely perform background work using HttpContext data, do the following:

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. Instead, it passes the required data. In the following example, call SendEmailCore to start sending e-mail. Pass correlationId to SendEmailCore instead of HttpContext. Code execution does not wait for SendEmailCore 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)
  {
    ...
  }
}

Related articles: