ASP.Net 5 MVC 6-如何使用FromBody在POST上返回无效的JSON消息? [英] ASP.Net 5 MVC 6 - how to return invalid JSON message on POST using FromBody?

查看:307
本文介绍了ASP.Net 5 MVC 6-如何使用FromBody在POST上返回无效的JSON消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.Net 4.5.1创建带有MVC 6的ASP.Net 5应用程序.我有一个POST方法,该方法使用FromBody参数自动获取对象.

I am creating an ASP.Net 5 application with MVC 6, using .Net 4.5.1. I have a POST method that uses a FromBody parameter to get the object automatically.

[HttpPost]
public IActionResult Insert([FromBody]Agent agent)
{    
    try
    {
        var id = service.Insert(agent);
        return Ok(id);
    }
    catch (Exception ex)
    {
        return HttpBadRequest(ex);
    }
}

这只是一个概念上的证明,成功时我不会仅返回id,而错误时则不会返回完整的异常.

This is just a proof a concept, I won't return only the id on success or the full exception on error.

发送有效的JSON后,一切正常.但是,当发送无效的JSON时,在调试过程中会出现异常:

When a valid JSON is sent everything works fine. However when an invalid JSON is sent, I get an exception during debug:

引发的异常:"Newtonsoft.Json.JsonReaderException"在 Newtonsoft.Json.dll

Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll

其他信息:解析值后,出现意外字符 遇到了:l.路径名称",第2行,位置20.

Additional information: After parsing a value an unexpected character was encountered: l. Path 'Name', line 2, position 20.

问题是出现此错误后,通常会调用该方法,但参数为null,并且不会传播异常.

The problem is that after this error, the method is called normally, but with a null parameter, and the exception doesn't propagate.

我可以检查是否为空并返回一条通用消息,但是它不如原始消息有用,原始消息包含重要信息,例如标签名称和无效字符的位置.

I could check for null and return a generic message, but that is not as useful as the original message, which has important information, such as the tag name and position of the invalid character.

因此,我想捕获此异常并将其返回给HTTP调用方.我怎么做?像这样:

So I want to capture this exception and return it to the HTTP caller. How do I do that? Something like this:

{"error": "After parsing a value an unexpected character was encountered: l. Path 'Name', line 2, position 20"}

我知道我可以在try/catch块中手动捕获和反序列化JSON,但这对我来说是不可接受的.我想这样做,并继续使用FromBody,我觉得它很有用.

I know I could capture and deserialize the JSON manually inside a try/catch block, but that is not acceptable for me. I want to do it and continue using FromBody, which I find very productive.

推荐答案

默认情况下,默认JsonInputFormatter会在遇到错误时返回空模型-但它将填充所有异常的ModelState.

The default JsonInputFormatter will in fact return a null model upon encountering an error - but it will populate ModelState with all exceptions.

因此,您可以通过深入研究ModelState来访问所有遇到的错误:

So you have access to all encountered errors by digging into ModelState:

[HttpPost]
public IActionResult Insert([FromBody]Agent agent)
{
    if (!ModelState.IsValid)
    {
        var errors = ModelState
            .SelectMany(x => x.Value.Errors, (y, z) => z.Exception.Message);

        return BadRequest(errors);
    }

    // Model is valid, do stuff.
}

上面的输出是所有异常消息的数组,例如:

Output of above is an array of all exception messages, e.g.:

[
    "After parsing a value an unexpected character was encountered: l. Path 'Name', line 2, position 20",
    "Another exception message..."
]

查看全文

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