首页 文章

Web API模型验证问题

提问于
浏览
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 - 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时,我没有看到Model验证器拾取了ErrorMessage .

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; }
    }
    

相关问题