Hosting multiple product APIs in single ASP.NET Core WebAPI Service

别说谁变了你拦得住时间么 提交于 2019-12-23 01:38:28

问题


I am designing an ASP.NET Core based Web API, which needs to support multiple variants of my product, let's say based on a license or the variety which it was installed.

Instead of going for multiple services for each type of product, I thought of a single service which houses/hosts multiple Endpoints or URLs. I will make this configurable in the appsettings.json at the time of installation.

I am aware of the UseUrls on creating the WebHost, but can I bind the specific URL in a set of URLs to specific Controllers?

Code:

WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:5000;http://localhost:5001;https://localhost:5002")

Expect

https://localhost:5000/ --> Product1Controller
https://localhost:5001/ --> Product2Controller
https://localhost:5002/ --> Product2Controller

I am new to the ASP.NET Core, please help me if this is achievable or not. Thanks in advance.


回答1:


A workaround is to add custom Constraint on api controller which is enabled with specific port.

1.Create a PortActionConstraint class:

[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)
    {
        //external port
        var externalPort = routeContext.HttpContext.Request.Host.Port;
        //local port 
        var localPort = routeContext.HttpContext.Connection.LocalPort;
        //write here your custom logic. for example  
        return Port == localPort;
    }
}

2.Add attribute with correspond port number on all controller like

[PortActionConstraint(5000)]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase


来源:https://stackoverflow.com/questions/56288153/hosting-multiple-product-apis-in-single-asp-net-core-webapi-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!