[英].net 6 web api - bad "Content-Type" property in request body - return 400 status instead of 500
I have an Attachments
json array in the request payload, and each attachment has three properties:我在请求负载中有一个Attachments
json 数组,每个附件都有三个属性:
Name
- string and holds the name of the file to be attached. Name
- 字符串并包含要附加的文件的名称。
ContentType
- System.Net.Mime.ContentType and holds the mediatype info of the file and ContentType
- System.Net.Mime.ContentType 并保存文件的媒体类型信息和
FileData
- string and holds base64encoded string of contents of the file/attachment. FileData
- 字符串并保存文件/附件内容的 base64 编码字符串。
Whenever ContentType
is null/empty
I see that the control does not even hit the controller, but the API is sending a 500 internal server error
, and the error message in the response is not helpful for the client:每当ContentType
为null/empty
时,我看到控件甚至没有命中 controller,但 API 正在发送500 internal server error
,并且响应中的错误消息对客户端没有帮助:
Message: This property cannot be set to an empty string. (Parameter 'value')
Is there a way to let the API pass through whatever value is entered for this property( mediaType
in ContentType
) and I would like to do the validation in the API for this property and throw a 400 with a proper message.有没有办法让 API 通过为此属性输入的任何值( ContentType
中的mediaType
),我想在 API 中为此属性进行验证,并抛出 400 和正确的消息。 Below is the request body that is causing above error:以下是导致上述错误的请求正文:
"Attachments": [
{
"Name": "Something.txt",
"ContentType": {
"Boundary": null,
"CharSet": null,
"MediaType": "", //this is causing the above error and I would like this one to be a bad request not a internal server error.
"Name": "SampleContentType",
"Parameters": [
{
"Key": "name",
"Value": "SampleContentType"
}
]
},
"FileData": "some base64 encoded string here"
}
]
One solution to this is to use a custom ContentType model which mimics the one being used, do the validation then map it to the original one, but I want to understand why the API is throwing 500, before it even hits the controller.一种解决方案是使用自定义 ContentType model,它模仿正在使用的 ContentType,然后将其验证为 map 到原始类型,但我想了解为什么 API 在它到达 controller 之前抛出 500。
Use the ConsumesAttribute
to let the framework check it.使用ConsumesAttribute
让框架检查它。
[Consumes("multipart/form-data")] // example
public async Task<IActionResult> MyAction { ... }
This will return a 415 by default if the Consumes
criteria is not met.如果不满足Consumes
标准,这将默认返回 415。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.