1

根据这篇文章ASP.NET - Model Validation,我应该可以根据我的模型中的数据注释对模型绑定过程中遇到的错误进行很好的描述。好吧,虽然验证工作正常,但它并没有为我提供很好的错误,而是提供了 JSON 解析错误。

这是我的模型:

public class SimplePoint
{
    [Required(ErrorMessage="MonitorKey is a required data field of SimplePoint.")]
    public Guid MonitorKey { get; set; }

    public int Data { get; set; }
}

这是我的验证过滤器:

public class ModelValidationFilterAttribute : ActionFilterAttribute
{
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request
                    .CreateErrorResponse(HttpStatusCode.BadRequest,                                                                                                
                        actionContext.ModelState);
            }
        }
    }

我必须删除 InvalidModelValidationProvider ,如这篇文章中所述:ASP.NET - 问题- Global.asax Application_Start 方法中的此代码退出:

GlobalConfiguration.Configuration.Services.RemoveAll(
    typeof (System.Web.Http.Validation.ModelValidatorProvider),
    v => v is InvalidModelValidatorProvider);

这是我使用 Fiddler 的请求:

POST http://localhost:63518/api/simplepoint HTTP/1.1
User-Agent: Fiddler
Host: localhost:63518
Content-Length: 28
Content-Type: application/json; charset=utf-8

{"MonitorKey":"","data":123}

这是我的控制器的回复:

HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcTG9jYWwgVmlzdWFsIFN0dWRpbyBwcm9qZWN0c1xKaXREYXNoYm9hcmRcSml0RGFzaGJvYXJkLldlYi5Nb25pdG9    ySG9zdFxhcGlcc2ltcGxlcG9pbnQ=?=
X-Powered-By: ASP.NET
Date: Fri, 22 Mar 2013 21:55:35 GMT
Content-Length: 165

{"Message":"The request is invalid.","ModelState":{"data.MonitorKey":["Error converting value \"\" to type 'System.Guid'. Path 'MonitorKey', line 1, position 16."]}}

为什么我的数据注释中没有出现错误消息(即“MonitorKey 是 SimplePoint 的必需数据字段”)?在我的验证过滤器中分析 ModelState,我没有看到模型验证器接收到 ErrorMessage。

4

1 回答 1

2

似乎答案就像使模型属性可以为空一样简单。这样,他们将通过 JSON 验证,并且基于数据注释的数据模型验证将生效:

public class SimplePoint
{
    [Required(ErrorMessage="MonitorKey is a required data field of SimplePoint.")]
    public Guid? MonitorKey { get; set; }

    [Required]
    public int? Data { get; set; }
}
于 2013-03-22T22:12:23.383 回答