簡體   English   中英

.net 6 web api - 請求正文中的錯誤“Content-Type”屬性 - 返回 400 狀態而不是 500

[英].net 6 web api - bad "Content-Type" property in request body - return 400 status instead of 500

我在請求負載中有一個Attachments json 數組,每個附件都有三個屬性:

Name - 字符串並包含要附加的文件的名稱。

ContentType - System.Net.Mime.ContentType 並保存文件的媒體類型信息和

FileData - 字符串並保存文件/附件內容的 base64 編碼字符串。

每當ContentTypenull/empty時,我看到控件甚至沒有命中 controller,但 API 正在發送500 internal server error ,並且響應中的錯誤消息對客戶端沒有幫助:

Message: This property cannot be set to an empty string. (Parameter 'value')

有沒有辦法讓 API 通過為此屬性輸入的任何值( ContentType中的mediaType ),我想在 API 中為此屬性進行驗證,並拋出 400 和正確的消息。 以下是導致上述錯誤的請求正文:

"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"
    }
  ]

一種解決方案是使用自定義 ContentType model,它模仿正在使用的 ContentType,然后將其驗證為 map 到原始類型,但我想了解為什么 API 在它到達 controller 之前拋出 500。

使用ConsumesAttribute讓框架檢查它。

[Consumes("multipart/form-data")] // example
public async Task<IActionResult> MyAction { ... }

如果不滿足Consumes標准,這將默認返回 415。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM