TL;博士
如果我的Content-Type "application/x-ourformat"绑定自定义TextInputFormatter无法解析输入,我希望将HTTP400(可能是415)返回给客户端。
从ReadRequestBodyAsync的实现返回到框架返回4xx HTTP响应的正确方法是什么?
我们为application/x-ourformat提供了一个自定义格式化程序,它构建在TextInputFormatter之上,如链接中所解释的那样。
上面MS中的示例进行了如下错误处理:
public override async Task<InputFormatterResult> ReadRequestBodyAsync(
InputFormatterContext context, Encoding effectiveEncoding)
{
...
return await InputFormatterResult.SuccessAsync(contact);
}
catch
{
logger.LogError("Read failed: nameLine = {nameLine}", nameLine);
return await InputFormatterResult.FailureAsync();
}
}也就是说,如果输入的处理失败(异常),它将返回FailureAsync()。
但是,这不会导致HTTP400响应,相反,绑定到Api的输入对象将只是null。
引起400次答复的原因是:
ReadRequestBodyAsync中抛出异常context.ModelState.AddModelError("My Key", "Couldn't really understand you.");之前设置FailureAsync。但我既不明白哪一个是“正确的”,也不真正理解ModelError应该代表什么。
发布于 2022-11-11 07:38:20
我现在已经深入研究了ReadRequestBodyAsync的调用链。
最终,结果将在BindModelAsync中进行处理,其中:
// Formatter encountered an error. Do not use the model it returned.ModelState.AddModelError(modelBindingKey, exception是否因此,由于框架本身将在异常上设置一个ModelError,因此似乎至少设置ModelError本身更有用。
就像克丘里:
模型错误表示模型..。不满足约束或包含格式错误的数据。因此,它适用于你的情况。
发布于 2022-11-10 18:17:16
下面是一个样本答复。注意,200 OK位于http标头之前。HTTP头具有一个键和一个由冒号分隔的值。主体是在头部后面。内容长度是正文中的字节数。
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
ETag: "34aa387-d-1568eb00"
Accept-Ranges: bytes
Content-Length: 51
Vary: Accept-Encoding
Content-Type: text/plain
Hello World! My content includes a trailing CRLF.https://stackoverflow.com/questions/74392428
复制相似问题