Search code examples
blazor-webassembly.net-6.0kestrel-http-server

How to route requests on different ports to different controllers?


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 only half of the solution (the server side) is provided there. The missing part is how to configure the controllers to receive the modified route.

I'm very new to ASP.NET Core, so I'm probably missing something obvious. In fact I'm probably not even calling it the right thing.

What should I do to my controllers so that a routed request, as shown in the linked answer, reaches the appropriate controller?


Solution

  • I was able to resolve the port/controller mapping problem, for my case at least, by slightly modifying the suggested Use call:

    app = builder.Build();
    
    app.Use(async (context, next) =>
    {
      if (context.Connection.LocalPort == 80)
      {
        context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
        await context.Response.SendFileAsync(@"Pages\Static\Setup.htm");
      }
      else
      {
        await next();
      }
    });
    

    Or, as a bit leaner alternative:

    app = builder.Build();
    
    app.MapGet("/", (HttpContext context) =>
    {
      context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
      return File.ReadAllText(@"Pages\Static\Setup.htm");
    }).RequireHost("*:80");
    

    This works for my use case because I'm allowing only a single static page to be accessed on port 80, the user instructions for installing the Root CA. Once that task is done, everything else runs on 443 as normal.

    So in the end I didn't need to map to a controller at all. In fact, with that approach I was wondering how I was going to break out of the navigation framework to display only the standalone setup page. This solves both problems.

    YMMV