从ModelState中删除JSON.net序列化异常

Sim*_*tes 11 c# asp.net-mvc json.net asp.net-web-api

问题背景

为了避免重复验证逻辑,我遵循将服务器端ModelState错误推送到我的View Model(MVVM KnockoutJS)的模式.

因此按照惯例,我的KOViewModel 上的属性名称匹配我的Api正在暴露和期待的属性,因此我可以使用我编写的一个小的Knockout插件轻松地将一个映射到另一个.

<validation-summary params="vm: $data, class: 'alert alert-error'"></validation-summary>

...

<div class="control-group" data-bind="errorCss: {'error': spend }">
     <label class="control-label" for="spend">Spend</label>
     <div class="controls">
        <div class="input-prepend">
           <span class="add-on">$</span>
           <input type="text" data-bind="value: spend" id="spend" class="input-medium" placeholder="Spend USD" />
         </div>   
          <validation-message params="bind: spend, class: 'text-error'"></validation-message>
      </div>
</div>
Run Code Online (Sandbox Code Playgroud)

问题

问题对我来说,当JSON.Net串行化我通过和AJAX发送JSON,当它遇到异常就其加入到ModelState为与ExceptionModelError类.

响应示例:

{
  "message": "The request is invalid.",
  "modelState": {
    "cmd.spend": [
      "Error converting value \"ii\" to type 'System.Double'. Path 'spend', line 1, position 13.",
      "'Spend' must be greater than '0'."
    ],
    "cmd.Title": [
      "'Title' should not be empty."
    ]
 }
}
Run Code Online (Sandbox Code Playgroud)

问题因为这条消息并没有给出一个很好的用户体验:

Error converting value "ii" to type 'System.Double'. Path 'spend', line 1, position 13.
Run Code Online (Sandbox Code Playgroud)

事实上,我无法将此异常消息与我的验证消息分开,因为它们都在一个数组中.

我宁愿删除它并在我的ValidationClass中处理这个问题

我可以像这样手动删除它们,这是在ActionFilter中所以我只有这一次.

public class ValidateCommandAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ModelStateDictionary modelState = actionContext.ModelState;

            #if !DEBUG
                for (int i = 0; i < modelState.Values.Count; i++)
                {
                    ModelErrorCollection errors = modelState.ElementAt(i).Value.Errors;
                    for (int i2 = 0; i2 < errors.Count; i2++)
                    {
                        ModelError error = errors.ElementAt(i2);
                        if (error.Exception != null)
                        {
                            // TODO: Add Log4Net Here
                            errors.RemoveAt(i2);
                        }
                    }
                }
            #endif

            if (!modelState.IsValid)
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState); 
        }
    }
Run Code Online (Sandbox Code Playgroud)

我知道JSON.Net是高度可配置的,并且想要知道API中是否存在某个地方,我可以将其关闭或抑制它?

Jim*_*ies 2

您可以设置错误处理程序。例如(来自 json.net 文档),

List<string> errors = new List<string>();

List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
      '2009-09-09T00:00:00Z',
      'I am not a date and will error!',
      [
        1
      ],
      '1977-02-20T00:00:00Z',
      null,
      '2000-12-01T00:00:00Z'
    ]",
    new JsonSerializerSettings
    {
        Error = delegate(object sender, ErrorEventArgs args)
        {
            errors.Add(args.ErrorContext.Error.Message);
            args.ErrorContext.Handled = true;
        },
        Converters = { new IsoDateTimeConverter() }
    });

// 2009-09-09T00:00:00Z
// 1977-02-20T00:00:00Z
// 2000-12-01T00:00:00Z

// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected String, got StartArray.
// Cannot convert null value to System.DateTime.
Run Code Online (Sandbox Code Playgroud)