Logo

dev-resources.site

for different kinds of informations.

Reading Request Headers Across Multiple .NET Core API Controllers

Published at
5/4/2024
Categories
net
api
csharp
tutorial
Author
debug_mode
Categories
4 categories in total
net
open
api
open
csharp
open
tutorial
open
Author
10 person written this
debug_mode
open
Reading Request Headers Across Multiple .NET Core API Controllers

I was working on creating a .NET Core-based API and came across a requirement to read a particular request header across the API controllers.  To understand it better, let us say there are two API controllers,

  1.    InvoiceController 2.    ProductController

We need to read the value of a particular Request Header in both controllers.
 
To do that, add a middleware class; I am naming it RequestCodeMiddleware, as we will read a request header named-  “Request-Code.”

public class RequestCodeMiddleware
{
    private readonly RequestDelegate _next;
 
    public RequestCodeMiddleware(RequestDelegate next)
    {
        _next = next;
    }
 
    public async Task Invoke(HttpContext context)
    {
        // Read the request code here. This is just an example, replace it with your actual logic.
        var requestCode = context.Request.Headers["Request-Code"].FirstOrDefault();
        // Add the request code to the HttpContext
        context.Items["RequestCode"] = requestCode+"middle ware";
        // Call the next middleware in the pipeline
        await _next(context);
    }
}

Enter fullscreen mode Exit fullscreen mode

After creating the middleware class, register it to the API handling pipeline by adding the below code,


if (app.Environment.IsDevelopment())
{
    
     app.UseSwagger();
    
app.UseSwaggerUI();

}

app.UseMiddleware<RequestCodeMiddleware>();
app.UseHttpsRedirection();

app.MapControllers();

app.Run();
Enter fullscreen mode Exit fullscreen mode

Now, you can read the request header in a ProductController’s GET Action, as shown below.

public class product : ControllerBase
{
   
    [HttpGet]
    public string Get()
    {
        var requestCode = HttpContext.Items["RequestCode"] as string;
        return requestCode;
    }
}

Enter fullscreen mode Exit fullscreen mode

So far, so good; however, there is still a challenge: the above code must be duplicated to read the request header in the multiple Actions. To avoid that, we can read it inside the controller’s constructor; however, HttpContext is unavailable inside a controller’s constructor.
 
Another approach is to use IHttpContextAccesor.
 
To use IHttpContextAccesor, register it in the API startup pipeline as shown below,

builder.Services.AddHttpContextAccessor();
Enter fullscreen mode Exit fullscreen mode

Now, in the InvoiceController's constructor, you can inject IHttpContextAccesor to read the request header, as shown in the code listing below.

public class invoice : ControllerBase
    {
 
        private readonly IHttpContextAccessor _httpContextAccessor;
        private string _requestCode;
 
        public invoice(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _requestCode = _httpContextAccessor.HttpContext.Items["RequestCode"] as string;
        }
 
     // Your action methods..
     // GET: api/<invoice>
        [HttpGet]
        public string Get()
        {
            return _requestCode;
        }
      }

Enter fullscreen mode Exit fullscreen mode

In this way, we can read a request header in multiple controllers.  I hope you find this post helpful. Thanks for reading.

net Article's
30 articles in total
Favicon
Implementing JWT Authentication in .NET API
Favicon
ASP.NET MVC Suite Update: Aligning with .NET Changes
Favicon
Building a React CRUD App with a .NET API
Favicon
Exploring Records in C#.
Favicon
Stack vs Heap in C#: Key Differences and Usage
Favicon
DLL injection of managed code into native process
Favicon
Syncfusion Visual Studio Extensions Are Now Compatible With .NET 9.0
Favicon
Syncfusion Now Supports .NET 9!
Favicon
Open Source Tools for .NET MAUI
Favicon
Introducing Syncfusion’s First Set of Open-Source .NET MAUI Controls
Favicon
Bootcamp De Backend Com .NET Gratuito DIO + Randstad
Favicon
Building a Vue CRUD App with a .NET API
Favicon
Building an Angular CRUD App with a .NET API
Favicon
Bootcamp De Backend Com .NET Gratuito De DIO + Randstad
Favicon
Unlock Efficient Data Exchange: Import & Export Excel in ASP.NET Core
Favicon
How I Access the Dark Web Using This Search Engine 🔮
Favicon
Building a File Upload API in .NET
Favicon
EF Core 6 - This SqlTransaction has completed; it is no longer usable.
Favicon
Implement data validation in .NET
Favicon
Create a pagination API with .NET
Favicon
Create an API for DataTables with .NET
Favicon
Getting Started with .NET Aspire: Simplifying Cloud-Native Development
Favicon
Create a CRUD API with .NET
Favicon
Cultivating Trust and Innovation: Top 10 .NET Development Partners You Can Rely On
Favicon
Bootcamp De .NET Gratuito Com Oportunidade De Contratação
Favicon
Dapper mappings, which is best?
Favicon
Reading Request Headers Across Multiple .NET Core API Controllers
Favicon
Understanding DynamicData in .NET: Reactive Data Management Made Easy
Favicon
The Future of .NET Development: Skills and Expertise Needed in Tomorrow's Programmers
Favicon
🦙 Harnessing Local AI: Unleashing the Power of .NET Smart Components and Llama2

Featured ones: