Monday, July 10, 2023

ASP.NET Core How To Use IHttpContextAccessor in a custom component

 

IHttpContextAccessor

  • IHttpContextAccessor  interface is used to get HttpContext object. 
  • HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received.
  • HttpContext is available by default in controllers and views. Therefore, we shouldn't use IHttpContextAccessor in them. The ControllerBase class provides HttpContext to the derived class called Controller. Likewise, Razor page and view provides HttpContext.

Example to use IHttpContextAccessor in a component

How to use IHttpContextAccessor in a custom component is explained through following example. A service is a custom component example. We create a service in ASP.NET Core project.

Do the following steps.

  1. Create project using ASP.NET Core Web App (Model-View-Controller) template.
    • Project name: WebAppMvc
    • Solution name: WebAppMvc
    • .NET Core version: 5.0
  2. Create Services folder in root of the project.
  3. Create Services/IPrinter interface.
  4. Create Services/Printer class.
  5. Add Printer and AddHttpContextAccessor services to IServiceCollection
  6. Use Printer service in the Home controller
Create Services/IPrinter interface. This contains a method to add a response header.

namespace WebAppMvc1.Services
{
    public interface IPrinter
    {
        void AddResponseHeader();
    }
}
Create Services/Printer class. Printer service class uses IHttpContextAccessor via dependency injection.

using Microsoft.AspNetCore.Http;

namespace WebAppMvc1.Services
{
    public class Printer : IPrinter
    {
        private readonly IHttpContextAccessor httpContext;

        public Printer(IHttpContextAccessor httpContext)
        {
            this.httpContext = httpContext;
        }

        public void AddResponseHeader()
        {
            httpContext.HttpContext.Response.Headers["blogger"] = "appliedk";
            httpContext.HttpContext.Response.WriteAsync("<h1>Response header added.
</h1>"); } } }
Register Services to IServiceCollection. We must register the service of IHttpContextAccessor apart from Printer service because Printer service has dependency upon IHttpContextAccessor service.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddHttpContextAccessor();
            services.AddTransient<IPrinter, Printer>();
        } 
Inject Printer service in HomeController.

Use DI to inject the service in the constructor of HomeController to consume the Printer service.


using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebAppMvc1.Services;

namespace WebAppMvc1.Controllers
{
    public class HomeController : Controller
    {
        private readonly IPrinter printer;

        public HomeController(IPrinter printer)
        {
            this.printer = printer;
        }
        public IActionResult Index()
        {
            printer.AddResponseHeader();
            HttpContext.Response.WriteAsync("Created header. PressF12
"); return View(); } } }

Run the application.We get the following output.

Press F12 to open the Chrome Developer console. We find that response header is added.

No comments:

Post a Comment

Hot Topics