【问题标题】:When WebApi serialization fails I would like the exception to bubble up not null my parameter当 WebApi 序列化失败时,我希望异常冒泡而不是 null 我的参数
【发布时间】:2016-05-26 22:34:00
【问题描述】:

我有一些自定义转换器已添加到我的 WebApi 项目的 SerializationSettings 中。当我在其中一个转换器中抛出异常时,我仍然会收到对 Action 的调用。根据哪个转换器失败,body 参数可以为 null 或设置的默认值。我遗漏了什么会导致 webapi 抛出该错误,以便我可以在更全局的级别上处理它?

webapi 版本:4.0.30506

json.net 版本:5.0.8

【问题讨论】:

  • 一般ModelState设置了反序列化相关的错误,所以你可以返回400 Bad Request带有ModelState信息,这样可以让客户端知道发生了不好的事情。

标签: asp.net-web-api json.net


【解决方案1】:

我遇到了同样的问题(但有一个解决方法)。您可以在 http 上下文中放置一个标志,稍后在 web api 中访问它并在那里处理它。您不能从自定义序列化程序中抛出异常并在 Web api 中捕获它。如果您试图覆盖它,它只会忽略异常并强制执行到 ReadJson 函数的末尾。

您可以将其用于 http 上下文 HttpContext.Current.Items["Error Info"] = "一些错误信息"

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer){
     ...            
     throw new Exception();
     ...

     ///comes here to the end directly                     
    }

【讨论】:

    【解决方案2】:

    如果您使用的是 owin web api,则 HttpContext.Current 为空。您可以使用此包 - OwinRequestScopeContext,它允许您使用也​​是每个请求的上下文。

    例如在JsonConverter中设置错误:

    OwinRequestScopeContext.Current.Items["error"] = exception;
    

    然后在你的控制器中得到错误:

    var ex = OwinRequestScopeContext.Current.Items["error"] as Exception;
    

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 2014-04-25
      • 2019-10-29
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2015-07-03
      相关资源
      最近更新 更多