Home > Software design >  How to configure Middleware to Blazor app
How to configure Middleware to Blazor app

Time:02-17

I there,

I've a Blazor app here that I would like to add Middleware class to it. but I can't find the startup.cs/IApplicationBuilder to add it.

My project only have a Program.cs class with a void Main method.

So how to configure a Middleware? Just adding a class named Startup.cs did not do the trick.

VS 2022/ .Net 6.0

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.AspNetCore.Mvc.Infrastructure;
// [other using]

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder
            .CreateDefault(args);
        
        builder.RootComponents.Add<App>("#app");

        builder.Services
            .AddTransient<DevicePresentationService>()
            // [other Service registration]

        builder.Services.AddOidcAuthentication(options =>
        {
            builder.Configuration.Bind("Auth0", options.ProviderOptions);
            options.ProviderOptions.ResponseType = "code";
        });

        var webAssemblyHost = builder.Build();
        
        webAssemblyHost.RunAsync();  
    }
}

CodePudding user response:

So how to configure a Middleware?

Middleware runs on the server. You posted the startup code for the Client.

Middleware is 'not applicable' in a Browser based app.

CodePudding user response:

This is the new structure in .Net 6. You need to add all previous Startup.cs logic to Program.cs

To add your middleware, add: var app = builder.Build(); and app.MyMiddleware();

Make sure the entire namespace of the Middleware is added to your usings at the top of your file, or in global usings.

Documentation

EDIT: I didn't see that this a web assembly Blazor application. @Henk Holterman is correct, you cannot use middleware on a client only application. You will need to add the middleware to your Server.

  • Related