如何根据可能值的数组限制 WebApi 路由参数

How to restrict a WebApi route parameter based on an array of possible values

我正在为以下路由构建 WebApi v.2 方法:

[Route("api/{entityName}/logo/{entityId}/{size:char}")]
public HttpResponseMessage GetLogo(string entityName, string entityId, char size) {...}

现在,我需要将 size 参数限制为三个字符之一:sml。如果 size 不是其中之一,我不希望匹配这条路线。

可能吗?

我认为这样的方法可能有效

  [Route("api/{entityName}/logo/{entityId}/{size:regex(^[sml]?$)}")]

您可以使用 Shorthand 约束参考 类 在直接路由模板中使用,将约束添加到直接路由。

可在此处找到 shorthand 直接路由正则表达式 类 的完整列表

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints

Stack overflow 上一题类似题目 Regex in Route attribute - RESTful API ASP.NET Web API