![](/img/trans.png)
[英]Asp.net Client - Server POST and Response (405 Method Not Allowed)
[英]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.