我们有一些控制器,它们只希望处理GET请求。 POST到达时返回500,我宁愿返回405(Method Not Allowed)。有没有办法设置它,所以当收到POST时,控制器上的所有路由都返回405?一些控制器需要接受POST,因此它不能在IIS配置中(即配置为拒绝动词)。为了您的信息,该平台是Azure Web App。
我确实有一个有效的解决方案,但缺点是必须添加到每条路线,这似乎很麻烦。
[Route("example/route/{date:datetime}")]
[AcceptVerbs("GET", "POST")]
public Periods GetExampleRoute(DateTime date)
{
if (Request.Method.Method.Equals("POST"))
{
throw new HttpResponseException(HttpStatusCode.MethodNotAllowed);
}
... GET processing ...
}
答案 0 :(得分:3)
You could do an MVC ActionFilter
(similarly for Web Api, System.Web.Http
):
public class RestrictVerbsAttribute : ActionFilterAttribute
{
private string Protocol { get; }
public RestrictVerbsAttribute(string verb)
{
Protocol = verb;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.RequestContext.HttpContext;
var result = request.Request.HttpMethod.Equals(Protocol, StringComparison.OrdinalIgnoreCase);
if (!result)
{
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.MethodNotAllowed); //405
}
}
}
Which you can use at Controller
or Action
Level
[RestrictVerbs("GET")]
public class VerbsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
POSTing to any Action in controller:
Hth...