4

I would like requests on different ports (80 and 443 in my case) to be routed to different controllers.

I see a suggested technique in this answer, but the code is outdated under .NET 6. UseMvc() is no longer used in the code provided by the Blazor/ASP.NET project templates.

Here's the boilerplate Program.cs code from a new Blazor WASM project:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

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.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");

app.Run();

Given the lack of a UseMvc() call, as indicated in the linked answer, where in this code would I put the suggested app.Use() call?

InteXX
  • 6,135
  • 6
  • 43
  • 80

2 Answers2

2

We use this to configure a classic API in our project:

app.UseEndpoints(endpoints => {
    endpoints
        .MapControllers()
        .RequireAuthorization();
});

We do not setup the port to be used, but I think the option could be available. I just found an interesting article that could help you: https://andrewlock.net/how-to-automatically-choose-a-free-port-in-asp-net-core/

// Dylan

Dylan El Bar
  • 783
  • 1
  • 14
  • Thanks, but I'm still new enough to ASP.NET Core that I'm afraid you've totally lost me (at least in the context of the task at hand). That said, I'll study up on what you've provided. Thanks. – InteXX Mar 16 '22 at 17:53
1

I ended up putting the Use call first in line, before anything else:

app = builder.Build();
app.Use(async (context, next) => { ... });

Here's the full solution.

InteXX
  • 6,135
  • 6
  • 43
  • 80