0

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
InteXX
  • 6,135
  • 6
  • 43
  • 80
  • Use a reverse proxy. – paladin Mar 15 '22 at 11:22
  • `reverse proxy` Does this mean IIS or other component external to my app? If so, I don't have that option. It's a retail app, so everything must be self-contained. – InteXX Mar 15 '22 at 11:26
  • OK, I found [this](https://microsoft.github.io/reverse-proxy/articles/getting-started.html). But how would I accomplish my goal using this reverse proxy? – InteXX Mar 15 '22 at 11:35
  • This very fine documentation describes how middleware might be implemented: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0#order – paladin Mar 15 '22 at 15:00
  • To be honest, I'm not very familiar with `.net`, I'm sorry. – paladin Mar 15 '22 at 15:02
  • That's a great resource. Good find. Thanks. – InteXX Mar 15 '22 at 16:16

1 Answers1

2

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

InteXX
  • 6,135
  • 6
  • 43
  • 80