gpt4 book ai didi

c# - 使用验证属性的 Web API 单字符串参数验证

转载 作者:太空狗 更新时间:2023-10-29 21:22:07 26 4
gpt4 key购买 nike

我知道您可以在模型上使用验证属性来验证它:

public class CommunicationQuery
{
[RegularExpression("[0-9]{0,10}", ErrorMessage = "Please enter a valid policy number")]
public string PolicyId { get; set; }
[RegularExpression("[0-9]{0,10}", 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 或手动验证使用正则表达式的 Controller 操作中的参数。

最佳答案

如果您使用属性路由来管理进入 Controller 的路径,你总是可以做这样的事情:

[Route("{Id:regex([0-9]{0,10})}")]
public async Task<HttpResponseMessage> Get(string id)
{

}

Attribute Routing overview documentation 中所述,存在各种路由约束.

它确实提出了一个问题,即为什么您接受长度为 10 的数字字符串作为您的 ID。将其解析为 int 时必须小心,不要超过 2,147,483,647,因为这是默认整数的最大大小。

关于c# - 使用验证属性的 Web API 单字符串参数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28736067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com