有時呼叫 API 時,對方回應的 HTTP Status 與我們所預期的不同。剛好最近有遇到,就順手記錄下來。
🔖 長話短說 🔖
415: Unsupported Media Type錯誤,請檢查Content-Type與Content與 API 要求的規範是否相同。
Status 415: Unsupported Media Type
基本上,會發生 HTTP Status 415,其原因不外乎是:
▶ Content-Type 設定錯誤,造成無法解析 Content 資料
若 API 要求的 Content-Type 是 application/json,但是實際上發送的是 application/x-www-form-urlencoded,就會發生這個錯誤。
可以從 Request Headers 內,看到 Content-Type 的設定。
▶ 傳送 Content 的資料格式錯誤,與 API 接收的資料不符
這個情況,有兩種可能:
要麼就是 Content 內的資料格式,與 Content-Type 設定的不符。API 要求 Json 的資料格式,但是發送的內容卻是 a=1&b=2 的格式,就會發生這個錯誤。
⚠️ 注意:若 API 要求的資料格式為數字,但是發送的內容卻是字串,在 ASP.NET Core 中通常會因為 Model Binding 失敗而回傳 400 Bad Request,而非 415。415 專指 Media Type (如 Header 的 Content-Type) 無法被 Server 識別或處理。
若 API 是要開發給自已使用,可以自行設定 Content-Type 與 Content 的格式。但若是提供給第三方的服務 callback 呼叫,就要配合第三方的發送格式。
application/x-www-form-urlencoded
[HttpPost("Verify")]
[Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> Callback(
[FromQuery] RedirectParameters parameters,
[FromForm] VerifyResult result)
{
// 略
}
若 Content-Type 是 application/x-www-form-urlencoded,則要使用 [FromForm] 來接收。
application/json
[HttpPost("Verify")]
public async Task<IActionResult> Callback(
[FromQuery] RedirectParameters parameters,
[FromBody] VerifyResult result)
{
// 略
}
若 Content-Type 是 application/json,則要使用 [FromBody] 來接收。
補充資料
▶ 延伸閱讀
💡 互動時間 處理 API 串接時最怕遇到含糊不清的 Status Code!你最近開發 API 有遇過什麼奇怪或難纏的 HTTP 錯誤代碼嗎?歡迎在留言區分享你的踩坑經驗,一起討論交流!
💬 留下你的想法
有問題、不同看法,或是你踩過類似的坑?歡迎留言討論,我會盡量回覆。