Created
July 8, 2021 08:10
-
-
Save marklagendijk/ddd60d1056675e0bcb202c0954f5c64b to your computer and use it in GitHub Desktop.
.NET Core Response Header Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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