发送BadRequest(ModelState)时,Postman中的“无法得到任何响应”而不是XML格式的ModelState错误

时间:2017-11-03 14:56:54

标签: asp.net-core asp.net-core-webapi

原谅我的无知,这是我第一次尝试ASP.Net核心WebAPI。我正在使用AspNetCore.MVC 1.1.4,以防相关。我正在使用Postman测试我的API。

我有一个简单的HttpPost,它会发回预期的400 Bad Request。对于此测试,我发送格式错误的XML,因此我的hostMessage没有正确反序列化。客户希望以XML格式发送和接收所有消息。

[HttpPost("Message")]
public IActionResult ReceiveMessage([FromBody] HostMessage hostMessage)
{
    if (hostMessage == null)
    {
        return BadRequest();
    }
    return Ok();
}

这让我得到了很好的预期回应。 Valid expected Bad Request 当我更改代码以便它将返回错误。

[HttpPost("Message")]
public IActionResult ReceiveMessage([FromBody] HostMessage hostMessage)
{
    if (hostMessage == null)
    {
        return BadRequest(ModelState);
    }
    return Ok();
}

我期望获得状态400错误请求,但在模型状态中找到异常(反序列化对象时出错)但是我得到“无法得到任何响应”

模型状态错误: Model State Error expected

实际邮递员回应: Actual Postman Response

所以问题是,为什么当我将ModelState添加到错误请求时,它不再返回带有错误的预期错误请求,而只是说它无法获得任何响应。

预发布编辑? 好的,在写这篇文章时想通了。客户端想要XML中的所有内容。我的配置服务设置如下。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddMvcOptions(x => x.InputFormatters.Insert(0, new XmlDataContractSerializerInputFormatter()))
        .AddMvcOptions(x => x.OutputFormatters.Insert(0, new XmlDataContractSerializerOutputFormatter()));
}

当我删除OutputFormatter时,我得到了JSON中的预期输出。 expected out, but in json

所以我更新了我的问题标题,现在问我如何在XML中返回预期的ModelState错误。

1 个答案:

答案 0 :(得分:0)

要回答有关如何获取该错误消息的特定问题,您需要将Errors对象遍历到ModelStateDictionary异常集合,并获取第一个异常消息,如对象中所示图中的树。

如果这就是您所追求的,我建议您使用 public static List<string> FindErrors(this ModelStateDictionary modelState) { List<string> errors = new List<string>(); foreach (var value in modelState.Values) { foreach(var error in value.Errors) { if (!string.IsNullOrWhiteSpace(error.ErrorMessage)) errors.Add(error.ErrorMessage); if (error.Exception != null) errors.Add(error.Exception.ToString()); // The ToString method gets the message you were looking for in this example } } return errors; } 的扩展方法来搜索并返回您想要的邮件。假设这是你想要的所有ModelState,如果它们存在你可能需要多条消息,我会尝试这样做:

return BadRequest(ModelState.FindErrors());

然后像这样使用: ion-backdrop

如果异常消息确实是您所追求的,那么这应该可以满足您的需求。