2017-01-02 92 views
1

我想处理过滤器中的验证错误。验证响应格式应该是这样的:如何手动反序列化ModelStateDictionary

{ 
     "message": "Validation errors in your request", 
     "errors": { 
      "email": [ 
        "The Email is required" 
       ], 
      "Address": [ 
        "The Address is required" 
       ] 
     } 
    } 

在我的过滤器,当我尝试以下操作:

public override void OnActionExecuting(ActionExecutingContext context) 
{ 
    if (!context.ModelState.IsValid) 
    { 
     context.Result = new BadRequestObjectResult(context.ModelState); 
    } 
} 

生成的响应格式为:

{ 
    "Email": [ 
      "The Email is required" 
     ], 
    "Address": [ 
      "The Address is required" 
     ] 
} 

message财产和errors信封缺失。我尝试了很多方法,但没有奏效。例如

public class ValidateModelAttribute : ActionFilterAttribute 
    { 
     public override void OnActionExecuting(ActionExecutingContext context) 
     { 
      if (!context.ModelState.IsValid) 
      { 
       var validationErrorResponse = new Dictionary<string, Object>(); 
       validationErrorResponse["message"] = "The request has validation errors"; 
       validationErrorResponse["errors"] = context.ModelState; 
       context.Result = new BadRequestObjectResult(validationErrorResponse); 
      } 
     } 
    } 

但响应包含modeldictionary的所有属性:

{ 
    "message": "The request has validation errors", 
    "errors": { 
    "Name": { 
     "childNodes": null, 
     "children": null, 
     "key": "Name", 
     "subKey": { 
     "buffer": "Name", 
     "offset": 0, 
     "length": 4, 
     "value": "Name", 
     "hasValue": true 
     }, 
     "isContainerNode": false, 
     "rawValue": null, 
     "attemptedValue": null, 
     "errors": [ 
     { 
      "exception": null, 
      "errorMessage": "The Name field is required." 
     } 
     ], 
     "validationState": 1 
    } 
    } 
} 

回答

1

ASP.NET核心的优势在于它是开源的,你可以随时查看代码,看看它做什么;)

让我们先来看看BadRequestObjectResult类(来源here

public BadRequestObjectResult(ModelStateDictionary modelState) 
     : base(new SerializableError(modelState)) 
{ 
} 

如我们所见,ModelStateDictionary的覆盖将模型状态传递到一个新的类SerializableError,然后将其传递给基类。

当我们看SerializableErrorsource我们看到,它是围绕IDictionary<string,object>的包装,它很好地格式化消息。

话虽这么说,这里是你需要使用的代码:这应该工作(没有测试)

public class ValidateModelAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext context) 
    { 
     if (!context.ModelState.IsValid) 
     { 
      var validationErrorResponse = new Dictionary<string, Object>(); 
      validationErrorResponse["message"] = "The request has validation errors"; 
      validationErrorResponse["errors"] = new SerializableError(context.ModelState); 
      context.Result = new BadRequestObjectResult(validationErrorResponse); 
     } 
    } 
} 

+0

非常感谢,工作就像一个魅力:) –