关于c#:如何通过带有数据注释的ModelState验证GET url参数

How to validate GET url parameters through ModelState with data annotation

我有一个Web API项目...我想尊重REST原则,所以我应该只有GET方法和POST方法...
我必须进行搜索,所以我认为这与GET方法匹配,因为在搜索之后,我得到了结果并将其显示在页面中...如果找不到任何内容,则必须创建对象...此操作是POST ...

现在我有一个问题...我必须验证搜索的过滤器,因为过滤器是税码和字母数字代码(6个字符)...我已经完成了客??户端验证。现在,我应该进行服务器端验证。

到目前为止,我们已经使用数据注释来验证请求,但这是GET ...,因此我的方法具有以下签名:

1
2
3
4
5
6
7
8
[HttpGet]
public IHttpActionResult GetActivationStatus(string taxCode, string requestCode)
{
    if (ModelState.IsValid)
    {
         ...
    }
}

但是如何使用数据注释来验证我的ModelState?

谢谢


创建自己的模型...

1
2
3
4
5
6
7
public class YourModel
{
    [//DataAnnotation ...]
    public string taxCode { get; set; }
    [//DataAnnotation ...]
    public string requestCode { get; set; }
}

并更改您的服务器端控制器的签名:

1
2
3
4
5
6
7
8
[HttpGet]
public IHttpActionResult GetActivationStatus([FromUri] YourModel yourmodel)
{
    if (ModelState.IsValid)
    {
         ...
    }
}

如果您的客户端代码已经起作用,则无需更改它。请注意,模型的属性与您现在传递的参数(string taxCode, string requestCode)相同...区分大小写...

编辑:
我的意思是,您可以通过以下方式调用您的控制器:

http:// localhost / api / values /?taxCode = xxxx