Web API模型验证问题

时间:2013-03-22 22:08:16

标签: c# asp.net-mvc-4 asp.net-web-api

根据这篇文章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 - Issue - 此代码在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。

1 个答案:

答案 0 :(得分: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; }
}