在 WebAPI C# 中请求反序列化期间捕获异常 [英] Capture exception during request deserialization in WebAPI C#

查看:16
本文介绍了在 WebAPI C# 中请求反序列化期间捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WebAPI v2.2,并且我正在使用 [FromBody] 属性让 WebAPI 将 JSON 反序列化到一个对象上.反序列化的目标类在内部方法上有一个 [OnDeserialized] 属性,如下所示:

I'm using WebAPI v2.2 and I am getting WebAPI to deserialise JSON onto an object using [FromBody] attribute. The target class of the deserialisation has a [OnDeserialized] attribute on an internal method, like this:

[OnDeserialized]
internal void OnDeserialisedMethod(StreamingContext context) {
    // my method code
}

我知道这个方法中的代码有问题,我已经通过它并找到了它.对我来说,问题是我根本没有例外.发生的情况是这个方法被跳出并且异常似乎被忽略了.我的控制器操作被调用并且我的目标对象没有正确填充,因为这个序列化方法没有被正确执行.

I know for a fact there is a problem with the code inside this method, I've stepped through it and found it. The problem for me is that I get no exception at all. What happens is this method gets jumped out of and the exception seems to be ignored. My controller action gets called and my target object is not properly populated because this serialisation method has not been correctly executed.

我的问题是;如何捕获在 WebAPI 中反序列化期间发生的异常?

My question is; how can I capture an exception that occurs during deserialisation in WebAPI?

推荐答案

我编写了一个过滤器(如各种评论中所建议的那样),它检查 ModelState 并在确实发生序列化错误时抛出异常.但请注意,这可能不仅包含序列化异常 - 可以通过在 Select 语句中指定具体异常类型来调整.

I've written up a filter (as suggested in various comments) that checks the ModelState and throws an exception if serialization errors did occur. Beware though, that this may not contain only serialization exceptions - that could be adjusted by specifing the concrete exception type in the Select statement.

public class ValidModelsOnlyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid)
        {
            base.OnActionExecuting(actionContext);
        }
        else
        {
            var exceptions = new List<Exception>();

            foreach (var state in actionContext.ModelState)
            {
                if (state.Value.Errors.Count != 0)
                {
                    exceptions.AddRange(state.Value.Errors.Select(error => error.Exception));
                }
            }

            if (exceptions.Count > 0)
                throw new AggregateException(exceptions);
        }
    }
}

我建议将此过滤器绑定到全局范围.我真的无法理解为什么可以忽略反序列化异常.

I suggest binding this filter on a global scope. I really can't fathom why it should be ok to ignore deserialization exceptions.

这篇关于在 WebAPI C# 中请求反序列化期间捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆