我知道您可以在模型上使用Validation属性来验证它,如下所示:
- public class CommunicationQuery
- {
- [RegularExpression("[0-9]{0,10}",ErrorMessage = "Please enter a valid policy number")]
- public string PolicyId { get; set; }
- [RegularExpression("[0-9]{0,ErrorMessage = "Please enter a valid member number")]
- public string MemberId { get; set; }
- }
- public IEnumerable<Communication> Get([FromUri]CommunicationQuery documentQuery)
- {
- }
但是可以使用诸如此类的验证属性来验证单个字符串吗?
- public async Task<HttpResponseMessage> Get([RegularExpression("[0-9]{0,10}")]string id)
- {
- }
这似乎不起作用.我能够做到这一点的唯一方法是创建包装器对象并使用[FromUri],在操作本身上使用自定义ActionFilterAttribute或使用正则表达式手动验证控制器操作中的参数.
解决方法
如果您使用属性路由来管理进入控制器的路径,
你可以做这样的事情:
你可以做这样的事情:
- [Route("{Id:regex([0-9]{0,10})}")]
- public async Task<HttpResponseMessage> Get(string id)
- {
- }
有各种路线约束,如Attribute Routing overview documentation所述.
它确实提出了一个问题,即为什么你接受一个长度为10的数字字符串作为你的id.在将其解析为不超过2,147,483,647的int时,您必须要小心,因为这是默认整数的最大大小.