簡體   English   中英

Web API模型驗證問題

[英]Web API Model validation issue

根據本文ASP.NET-模型驗證 ,我應該對基於模型中數據注釋的模型綁定期間遇到的錯誤有一個很好的描述。 好吧,雖然驗證有效,但它並沒有給我帶來很好的錯誤,而是給我提供了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時,我看不到Model驗證程序收到了ErrorMessage。

似乎答案很簡單,只要使模型屬性可為空即可。 這樣,他們將通過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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM