Search code examples
c#asp.net-coreblazor.net-9.0

Blazor UseAntiForgery Not Rendering Page


What does this actually mean, been fighting it for hours and can't figure out what its complaining about

InvalidOperationException: Endpoint / (/) contains anti-forgery metadata, but a middleware was not found that supports anti-forgery. Configure your application startup by adding app.UseAntiforgery() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAntiforgery() must go between them. Calls to app.UseAntiforgery() must be placed after calls to app.UseAuthentication() and app.UseAuthorization().

I run it locally in debug and it works absoloutely fine but when I do a dotnet publish and then run the app via command line, it fails to load the page with the above error.

This is my program.cs

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Mvc;
using MudBlazor.Services;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add MudBlazor services
builder.Services.AddMudServices();

// Add services to the container.
builder.Services
    .AddRazorComponents()
    .AddInteractiveWebAssemblyComponents();

builder.Services
    .AddControllers()
    .AddJsonOptions(opts =>
    {
        opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        opts.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    });

var app = builder.Build();

if (builder.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
    app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.UseAntiforgery();
app.UseEndpoints(e => e.MapControllers());
app.UseHttpsRedirection();
app.UseStaticFiles();

app.MapRazorComponents<App>()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(Foo.Bar.WebClient._Imports).Assembly);

app.UsePathBase("/foo/bar");

await app.RunAsync();

Solution

  • put the middleware app.UseHttpsRedirection(); before app.UseRouting();

    As stated in the document:

    UseAntiforgery is called after UseHttpsRedirection. A call to UseAntiforgery must be placed after calls, if present, to UseAuthentication and UseAuthorization.