Monday, July 10, 2023

ASP.NET Core Headers with ResultFilterAttribute


Headers, what we can do

  1. Add custom response header
  2. Add custom request header 
  3. Get request header value
  4. Get response header value
  5. Get list of request headers
  6. Get list of response headers etc.

Practical Examples

  1. Add a custom response header in action method using HttpContext
  2. Add a custom response header globally to all the responses using middleware in Startup class
  3. Add a custom response header in more than one action methods using ResultFilterAttribute class
  4. Add a custom response header in Index view using RazorPage.Context
  5. List all  response headers in Index view using RazorPage.Context
  6. Get a request header value, for example, of Authorization header and then its bearer token value

Add a custom response header In action method

Case1


using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebAppMvc1.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            HttpContext.Response.Headers["blogger"] = "appliedk";
            return View();
        }
    }
}

Case2


            app.UseStaticFiles();
            app.Use(async (context, next) =>
            {
                context.Response.Headers.Add("developer", "shri");
                await next();
            });
            app.UseRouting();

Output in Chrome Developer for case1 and case2

Case3

Step1. Add class AddResponseHeaderAttribute : ResultFilterAttribute class in Filters folder. Note that it inherits ResultFilterAttribute class. Override the OnResultExecuting method. Write the logic of adding response header in it.


using Microsoft.AspNetCore.Mvc.Filters;

namespace WebAppMvc1.Filters
{
    public class AddResponseHeaderAttribute : ResultFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            context.HttpContext.Response.Headers.Add("country", "India");
            base.OnResultExecuting(context);
        }
    }
}

Step2. In Home controller, create Get action. Apply the custom attribute AddResponseHeader on this Get action.

The advantage of attribute based header is that we can apply the attribute on all the actions where we need the header addition. The logic to add the header is in one place in the class which overrides the ResultFilterAttribute.


        [AddResponseHeader]
        public IActionResult Get()
        {
            // header will be added beause of AddResponseHeader attribute
            return View();  
        }

The response header country is added. Look the image below.

Case4

use RazorPage.Context as shown in the below code in Index view.


@{
    Context.Response.Headers.Add("ajeet","appliedk.blogspot.com");
}

Case5


@{
    ViewData["Title"] = "Home Page";
    var headers = Context.Request.Headers;
    var keys = headers.Keys;
    Context.Response.Headers.Add("ajeet", "appliedk.blogspot.com");
}

<h3>List of all @headers.Count Request headers</h3>
<table class="table table-striped">
    @if (true)
    {
        foreach (var key in keys)
        {
            <tr>
                <td>@key</td>
                <td>@headers[key]</td>
            </tr>
        }
    }
</table>

<h2>Using razorPage.Context to get HttpContext</h2>
<h3>@Context.Connection.LocalIpAddress.ToString()</h3>
<h3>@Context.Connection.LocalPort</h3>
<h3>@Context.Request.ContentType</h3>
<h3>@Context.Request.Host.Host</h3>

Case6 Get Bearer Token Based on Authentication Request Header


var authHeader = Request.Headers["Authorization"].FirstOrDefault();

if (authHeader != null && authHeader.StartsWith("Bearer", StringComparison.OrdinalIgnoreCase))
{
    var loginToken = authHeader.Replace("Bearer ", string.Empty, StringComparison.OrdinalIgnoreCase);
}

No comments:

Post a Comment

Hot Topics