I agree with @Ho3Ein that
if you want to add a custom header to all requests, middleware is the best way
but modifying Resposne
directly in middleware is discouraged. From Microsoft Doc.
Changes to HttpResponse after the response has started, throw an exception. For example, changes such as setting headers and a status code throw an exception.
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
});
So the better way to add a custom header in middleware is to use Response.OnStarting
callback like below:
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("X-Developed-By", "Your Name");
return Task.FromResult(0);
});
await next();
}
);