Search code examples
c#.netcorsblazor-webassembly.net-7.0

Blazor WASM Server Hosted CORS hosting


I have created a Blazor WASM server hosted project where I use Azure Active Directory for authorization. The source code can be found here: https://github.com/theodor349/WeeklyReview

The app works fine when running on localhost, but when I publish it, move the published files to my server, and run it there, then I get some weird behavior.

I just receive this:

enter image description here

And when I spin up a python3 -m http.server 5000 (Notice it is on the same port) then I have no problem.

enter image description here

I thought it might have something to do with CORS, but it still persists when I add AllowAny Origin, Header and Method.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddCors(options => options
.AddPolicy(name: allowedOrigins, builder =>
{
    builder.AllowAnyOrigin()
    .AllowAnyHeader()
    .AllowAnyMethod();
}));

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();
app.UseCors(allowedOrigins);
app.UseAuthorization();

Solution

  • As @user7994388 mentioned, the problem is with ip address that the app listens on. So, instead of listing on localhost it should listen on 0.0.0.0.

    I fixed it by spinning it up in docker container, and forwarding its port (in this case it changed to 80). enter image description here

    version: '3.3'
    services:
      weekly-review-app:
        image: <container-regestry-uri>/weeklyreview-server:latest
        container_name: weekly-review-app
        restart: always
        ports:
          - '5000:80'