Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose a set of endpoints only on an additional, separate port in ASP.NET Core application

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?

like image 569
Fabian Avatar asked Nov 14 '25 14:11

Fabian


1 Answers

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
like image 151
Eldar Avatar answered Nov 17 '25 03:11

Eldar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!