Mvc: How to separate controllers by ports inside selfhosted web service?

Created on 26 Sep 2018  路  5Comments  路  Source: aspnet/Mvc

Description of the problem:

I need to separate controllers by ports inside netcore2.0 selfhosted web service.

My configuration
Version of Microsoft.AspNetCore.Mvc : 2.0.1
Selfhosted service using Kestrel.
OS: Linux

Example:
There are 2 ports(p1 and p2) and 3 controllers(c1, c2, c3). Requirement scheme: c1 processes requests from p1, but c2 and c3 will processes requests from p2.

Is it available to do? If yes, them how can i do that?

PS pls mark this issue as question and sorry for my bad English

question

Most helpful comment

You could use an action constraint to do this:

```C#
[PortActionConstraint(5000)]
public class HomeController : Controller
{
...
}

[AttributeUsage(AttributeTargets.Class)]
public class PortActionConstraint : ActionMethodSelectorAttribute
{
public PortActionConstraint(int port)
{
Port = port;
}

public int Port { get; }

public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
    var port = routeContext.HttpContext.Request.Host.Port;
    return Port == port;
}

}
```

All 5 comments

Thanks for contacting us, @Frank591.
@pranavkm, can you please look into this? Is this somethign we support?

If you want the same process (web application) to process all requests, then you need a proxy in front of your application that will handle these. NGinx, HAProxy can do it quite easily.

You can also listen to multiple ports and filter the requests in a middleware. You can use the urls parameter of kestrel to add more input addresses, and I think you can use multiple ports there.

Thanks for answer, @sebastienros. Variant with load balancers is not available for me. I want to separeate requests inside single app. Can you give some example of middleware, that will sort request between controllers based on input port?

You could use an action constraint to do this:

```C#
[PortActionConstraint(5000)]
public class HomeController : Controller
{
...
}

[AttributeUsage(AttributeTargets.Class)]
public class PortActionConstraint : ActionMethodSelectorAttribute
{
public PortActionConstraint(int port)
{
Port = port;
}

public int Port { get; }

public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
    var port = routeContext.HttpContext.Request.Host.Port;
    return Port == port;
}

}
```

@pranavkm , thanks for answer! Will try to use that.

Was this page helpful?
0 / 5 - 0 ratings