Capture exception during request deserialization in WebAPI C#

前端 未结 3 1715
-上瘾入骨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 17:53

    I had exactly the same problem and bookmarked your question in hope that someone would provide a solution. I thought using ModelState implied rewriting some validations in the JSON model, but it just works, in fact it's simple and very well done. I didn't have to modify the model, just the controllers.

    My code from one of my controllers, StdResponse being the class used to provide the response with details if needed (in this case, for instance) :

    [HttpPost]
    public StdResponse Test([FromBody]StdRequest request)
    {
        if (ModelState.IsValid)
        {
            //Work on the data from the request...
        }
        else
        {
            //Retrieve the exceptions raised during deserialization
            var errors = ModelState.SelectMany(v => v.Value.Errors.Select(e => e.Exception));
    
            List messages = new List();
    
            foreach (Exception e in errors)
            {
                messages.Add(e.GetType().ToString() + ": " + e.Message);
            }
    
            return new StdResponse(exchangeVersion, "null", ExecutionResponse.WithError("StdRequest invalid", messages));
        }
    }
    

提交回复
热议问题