I have a typical ASP.NET Core application (.NET6) that is listening on the default HTTPS Port and provides the main API endpoints there.
What I'd like to do now is to add a set of endpoints that are only reachable via a different Host and Port, e.g. something like localhost:1234. This is for a kind of control plane that should have more restricted access than the main API, running it on a different port and restricting the host would allow a completely separate network configuration to secure it.
This should run in the same process as the main application, there are a few parts that get much easier if this control plane has access to the internal state of that process. So just running a separate process is not a good solution in my case.
I can make ASP.NET Core listen on additional ports, but that just combines everything and runs the same endpoints on both ports. What I need is to essentially run two separate sets of endpoints (and ideally middleware) within the same application.
How can I achieve that and set this up in ASP.NET Core?
Well, my first approach would be to use two separate applications that run on their own terms. You have mentioned that that the other services should access the state of the main application this is also something I would stay away from (Having a in-process state, which is not good for scaling too, with some other drawbacks) But if you prefer to stay on your current configuration you can have something like the below :
// start up configuration
app.MapControllers();
app.Use(async (ctx, next) =>
{
var port = ctx.Request.HttpContext.Connection.LocalPort;
if (port == 7050)
{
// Do not allow FooController
if (ctx.Request.RouteValues["controller"]?.ToString() == "Foo")
{
ctx.Response.StatusCode = 404;
return; // to prevent the other middlewares to run
}
}
else
{
// Allow only FooController
if (ctx.Request.RouteValues["controller"]?.ToString() != "Foo")
{
ctx.Response.StatusCode = 404;
return; // to prevent the other middlewares to run
}
}
await next(ctx);
});
app.Run();
Somewhere in your settings:
"applicationUrl": "https://localhost:7049;https://localhost:7050;", #launchSettings.json
or
"urls":"https://localhost:7049;https://localhost:7050;" #appSettings.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With