Skip to content

Instantly share code, notes, and snippets.

@marklagendijk
Created July 8, 2021 08:10
Show Gist options
  • Save marklagendijk/ddd60d1056675e0bcb202c0954f5c64b to your computer and use it in GitHub Desktop.
Save marklagendijk/ddd60d1056675e0bcb202c0954f5c64b to your computer and use it in GitHub Desktop.
.NET Core Response Header Middleware
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace MyApplication
{
public class ResponseHeaderMiddleware
{
private readonly RequestDelegate _next;
private readonly IDictionary<string, string> _headers;
public ResponseHeaderMiddleware(RequestDelegate next, IDictionary<string, string> headers)
{
_next = next;
_headers = headers;
}
public async Task InvokeAsync(HttpContext context)
{
foreach (var header in _headers)
{
context.Response.Headers[header.Key] = header.Value;
}
await _next(context);
}
}
public static class ResponseHeaderMiddlewareExtensions {
public static IApplicationBuilder UseResponseHeaders(this IApplicationBuilder builder, IDictionary<string, string> headers)
{
return builder.UseMiddleware<ResponseHeaderMiddleware>(headers);
}
}
}
namespace MyApplication
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseResponseHeaders(new Dictionary<string, string>
{
{"Referrer-Policy", "no-referrer"}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment