簡體   English   中英

ASP.NET覆蓋“不允許使用405方法” http響應

[英]ASP.NET override '405 method not allowed' http response

在ASP.NET WebAPI中,我有一個控制器/動作,可以使用GET動詞進行訪問。 如果我使用POST動詞查詢端點,則會得到標准405 method not allowed響應。

是否可以在不向控制器添加代碼的情況下攔截這種行為並注入自己的自定義響應而不是該響應呢? 或者也許以某種方式覆蓋了原始響應。 預期此行為將在整個應用程序中出現,因此我將不得不以某種方式全局設置此設置。

405的這種行為是由管道確定合適的控制器,然后通過命名約定或屬性來確定合適的方法確定的。 我看到兩種方法可以實現理想的結果,即自定義IHttpActionSelector或基本ApiController。

IHttpActionSelector的示例代碼:

public class CustomHttpActionSelector : IHttpActionSelector
{
    public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
    {
        var isPostSupported = false;

        //logic to determine if you support the method or not

        if (!isPostSupported)
        {
            //set any StatusCode and message here
            var response = controllerContext.Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "Overriding 405 here.");
            throw new HttpResponseException(response);
        }
    }

    ...
}

//add it to your HttpConfiguration (WebApiConfig.cs)
config.Services.Add(typeof(IHttpActionSelector), new CustomHttpActionSelector());

基本ApiController的示例代碼:

public abstract class BaseApiController<T> : ApiController
{
    public virtual IHttpActionResult Post(T model)
    {
        //custom logic here for "overriding" the 405 response
        return this.BadRequest();
    }
}

public class UsersController : BaseApiController<User>
{
    public override IHttpActionResult(User model)
    {
        //do your real post here
        return this.Ok();
    }
}

暫無
暫無

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

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