在单个 ASP.NET Core WebAPI 服务中托管多个产品 API [英] Hosting multiple product APIs in single ASP.NET Core WebAPI Service
问题描述
我正在设计一个基于 ASP.NET Core 的 Web API,它需要支持我的产品的多种变体,比如基于许可证或安装的种类.
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.
我没有为每种类型的产品提供多种服务,而是想到了一个包含/托管多个端点或 URL 的单一服务.我将在安装时在 appsettings.json 中进行配置.
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.
我知道 UseUrls 创建 WebHost,但我可以将一组 URL 中的特定 URL 绑定到特定控制器吗?
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?
代码:
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:5000;http://localhost:5001;https://localhost:5002")
期待
https://localhost:5000/ --> Product1Controller
https://localhost:5001/ --> Product2Controller
https://localhost:5002/ --> Product2Controller
我是 ASP.NET Core 的新手,如果可以实现,请帮助我.提前致谢.
I am new to the ASP.NET Core, please help me if this is achievable or not. Thanks in advance.
推荐答案
一种解决方法是在启用特定端口的 api 控制器上添加自定义约束.
A workaround is to add custom Constraint on api controller which is enabled with specific port.
1.创建一个PortActionConstraint
类:
[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.在所有控制器上添加具有对应端口号的属性,如
2.Add attribute with correspond port number on all controller like
[PortActionConstraint(5000)]
[Route("api/[controller]")]
[ApiController]
public class Product1Controller : ControllerBase
这篇关于在单个 ASP.NET Core WebAPI 服务中托管多个产品 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!