Capture exception during request deserialization in WebAPI C#

前端 未结 3 1711
-上瘾入骨i
-上瘾入骨i 2020-12-09 17:32

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]

3条回答
  •  失恋的感觉
    2020-12-09 18:07

    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();
    
                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.

提交回复
热议问题