1

我使用model validation我的網絡API和我有以下的自定義模型爲例定製驗證屬性模型驗證與

public class Address 
{ 
    [Required(ErrorMessage = "The firstName is mandatory")] 
    [EnhancedStringLength(100, ErrorCode = "1234556", ErrorMessage = "firstName must not exceed 100 characters")] 
    public string FirstName { get; set; } 
} 

public sealed class EnhancedStringLengthAttribute : StringLengthAttribute 
{ 
    public EnhancedStringLengthAttribute(int maximumLength) : base(maximumLength) 
    { 
    } 

    public string ErrorCode { get; set; } 
} 

在我的模型驗證過濾器我有以下作爲一個例子

public class ModelValidationAttribute : ActionFilterAttribute 
{ 

    public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) 
    { 
     if (actionContext.ModelState.IsValid) 
     { 
      return; 
     } 

     var errorViewModels = actionContext.ModelState.SelectMany(modelState => modelState.Value.Errors, (modelState, error) => new 
     { 
      /*This doesn't work, the error object doesn't have ErrorCode property 
      *ErrorCode = error.ErrorCode, 
      **************************/ 
      Message = error.ErrorMessage, 
     }); 


     actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errorViewModels); 

     await Task.FromResult(0); 
    } 
} 

我想實現的是當輸入模型未通過驗證(例如FirstName字符串長度超過100的情況下),我想輸出錯誤代碼以及錯誤消息,如下所示:

[{"errorCode":"1234556","message":"firstName must not exceed 100 characters"}] 

但問題是在訪問過濾器中的ModelState時ErrorCode不可用,在這種情況下的錯誤對象是類型System.Web.Http.ModelBinding.ModelError並且不包含errorcode屬性,我該如何實現?

回答

0

您正在擴展ActionFilterAttribute,但您確實想要擴展ValidationAttribute。

僅供參考:ASP.NET MVC: Custom Validation by DataAnnotation

+0

嘿,那不是我的意思。我想將我的自定義屬性(ErrorCode)添加到驗證屬性,並且我希望它在ModelState中可用,清除? – Ming

+0

我告訴你,這不是解決這個問題的正確方法。您將無法將該屬性添加到ModelState中,而不會出現醜陋的解決方法。 – LaCartouche