我有一个带有一些预定义路线模板的基本控制器:
[Authorize]
[ApiController]
[Produces(MediaTypeNames.Application.Json)]
public abstract class TenantControllerBase : ControllerBase
{
public const string DefaultRoute = "api/s/{serviceId:int}/[controller]";
private readonly ITenantContext _tenantContext; // Extracts the value of serviceId in a middelware
protected int ServiceId => _tenantContext.ServiceId;
protected TenantControllerBase(ITenantContext tenantContext)
{
_tenantContext = tenantContext ?? throw new ArgumentNullException(nameof(tenantContext));
}
}
想法是能够使用中间件检索 serviceId 并使其可供从 TenantControllerBase 继承的所有控制器使用,而不必每次都在操作中明确提及它作为输入参数:
[Route(DefaultRoute)]
public class SomeTenantController : TenantControllerBase
{
public SomeTenantController(ITenantContext tenantContext) : base(tenantContext) { }
[HttpGet("{type}")]
public async Task<IActionResult> Get(string type, CancellationToken cancellationToken)
{
var serviceId = this.ServiceId;
// ...
return Ok();
}
}
问题在于 swagger 规范将 serviceId 的类型设置为字符串,而不是路由模板中指定的整数:
"/api/s/{serviceId}/SomeTenant/{type}": {
"get": {
"tags": [
"SomeTenant"
],
"parameters": [
{
"name": "type",
"in": "path",
"required": true,
"style": "simple",
"schema": {
"type": "string"
}
},
{
"name": "serviceId",
"in": "path",
"required": true,
"style": "simple",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Success"
}
}
}
},
据我所知,让 swagger 明白 serviceId 是一个整数的唯一方法是将其显式添加到操作方法签名中:
[HttpGet("{type}")]
public async Task<IActionResult> Get(
string type,
int serviceId,
CancellationToken cancellationToken)
{
// serviceId is the same as the base field this.ServiceId;
// ...
return Ok();
}
有什么方法可以强制swagger根据路由模板中指定的值类型设置值类型
"api/s/{serviceId:int}/[controller]"
而不必在action方法签名中显式添加?