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

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

问题描述

我使用的WebAPI V2.2和我得到的WebAPI到deserialise JSON到使用[FromBody]属性的对象。目标类deserialisation都有一个内部方法[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
}

我知道的一个事实是存在这个方法里面的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 deserialisation期间发生异常?

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

推荐答案

我已经写了一个过滤器(如各种意见建议)来检查的ModelState,并抛出,如果确实发生了错误的序列化的异常。要小心的是,这可能并非只包含序列化的例外 - 这可以通过specifing在选择语句具体的异常类型进行调整

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天全站免登陆