Search code examples
http-headersblazor-webassembly.net-6.0

Adding headers to every response of an Blazor WASM in .NET 6


I created a simple (so far) Blazor WebAssembly application in .NET 6.

I'm currently adding additional HTTP requests to every response of the application and wanted to add an X-FRAME-OPTIONS header, but when searching on how to do it, I realized I don't know how to approach it.

For starters here's my Program.cs file:

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MyApplicationNamespace;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

await builder.Build().RunAsync();

When reading this webpage I learned about using middleware inside

app.Use(async (context, next) =>
{
    context.Response.Headers.Add("x-my-custom-header", "middleware response");
    await next();
});

I do understand from this site that in order to use the Use function I can do this:

var app = builder.Build();
app.Use();

Or that I can just pass a delegate function

app.Run(async context =>
{
    await context.Response.WriteAsync("Hello from 2nd delegate.");
});

Point is, in Blazor WASM I don't have a Run method, and RunAsync does not take parameters.

I'm not sure where to go from here to add a header?

Am I missing a NuGet passage?


Solution

  • From what I've learned from this person on Twitter:

    The Blazor WASM application is the client. It lives exclusively within the browser. It is receiving responses from a web server, and not "returning" anything. X-Frame-Options headers need to be set on the server, not by the application in the Browser.

    Do you mean that the web server should add these headers when it's delivering the (static) files of your Blazor application to the browser before it starts being executed there? You need to configure your web server (whatever it is) to send these headers then.

    Since I deployed my application as an Azure App Service I used Advanced Tools to edit out web.config inspired by this site.