簡體   English   中英

ASP .NET Web API 如何在不支持的媒體類型上返回錯誤

[英]ASP .NET Web API How to return error on unsupported media type

我的 Web API 控制器在其方法之一中處理某些第三方類

[HttpPost]
public IHttpActionResult CreateJob([FromBody] ThirdPartyCustomType item)
{
  //Something useful done here
}

它使用自定義媒體類型格式化程序進行解析,並擁有自己的媒體類型“application/json+customType”。

問題是當參數內容類型指定不正確時(例如“application/json”)。 Web API 使用另一個格式化程序來解析請求正文,然后當它嘗試創建 ThirdPartyCustomType 的實例時,它會失敗一些內部驗證並拋出 NullReferenceException。

當內容類型錯誤時,如何告訴 Web API 不要嘗試解析請求正文?

編輯:正如評論中的人建議我創建了一個中間件類,現在的問題是所有請求都在那里被捕獲,我需要此驗證僅適用於一個。 我認為我可以檢查中間件中的 Request.Path 並僅在它符合我的請求時才采取行動,但這似乎不是一個好的解決方案。

另一個編輯最后它看起來像這樣:

public class ContentTypeCheckMiddleWare : OwinMiddleware
{
    public ContentTypeCheckMiddleWare(OwinMiddleware next) : base(next)
    {
    }

    public async override Task Invoke(IOwinContext context)
    {
        if (context.Request.Path.Value.EndsWith("myRouteSuffix") && context.Request.Method == "POST")
        {
            var contentType = context.Request.ContentType;

            if (contentType != "application/json+customType")
            {
                context.Response.StatusCode = 416;
                await context.Response.WriteAsync(
                    "Invalid content type.");
            }
        }
        else
        {
            await Next.Invoke(context);
        }
    }
}

有沒有更好的辦法?

當返回類型為 IHttpActionResult 時,您可以使用內置響應類型,例如 Ok()、BadRequest() 或 NotFound(),對於其余狀態代碼,您可以使用 StatusCode(HttpStatusCode statuscode) 方法。

return StatusCode(HttpStatusCode.UnsupportedMediaType);

暫無
暫無

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

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