Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

How to add a custom HTTP response header in AspNet Zero? #8144


User avatar
0
alper created
Support Team

I'll show you how to add a new response header in AspNet Zero.

Note that if you want to add a request header in Angular like Pragma or Expires you can create a new HttpInterceptor. See the existing headers that are automatically being added to the request by the abp-ng2-module. https://github.com/aspnetboilerplate/abp-ng2-module/blob/d30ae5335e03e5c6d3e7858932f195376be91e6d/src/abpHttpInterceptor.ts#L239

Let's add Cache-Control header to all server responses! Create a new middleware for AspNet Core as below: Create a new class and name it ZeroSecurityHeadersMiddleware

ZeroSecurityHeadersMiddleware.cs

public class ZeroSecurityHeadersMiddleware
    {
        private readonly RequestDelegate _next;

        public ZeroSecurityHeadersMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            AddHeaderIfNotExists(httpContext, "Cache-Control", "no-cache");

            await _next.Invoke(httpContext);
        }

        private static void AddHeaderIfNotExists(HttpContext context, string key, string value)
        {
            if (!context.Response.Headers.ContainsKey(key))
            {
                context.Response.Headers.Add(key, value);
            }
        }
    }

Use this middleware in the Startup.cs after UseAbp().

Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            //Initializes ABP framework.
            app.UseAbp(options =>
            {
                options.UseAbpRequestLocalization = false; 
            });

            app.UseMiddleware<ZeroSecurityHeadersMiddleware>();
            
           //...
}


No answer yet!