我可以将控制器配置为拒绝所有 Post 方法吗?

Can I configure a controller to reject all Post methods?

我们有一些控制器预计只处理 GET 请求。当 POST 到达时,它 return 是 500,我宁愿 return 是 405(方法不允许)。有没有办法设置它以便在收到 POST 时控制器 return 405 上的所有路由?一些控制器需要接受 POST 所以它不能在 IIS 配置中(即配置为拒绝动词)。供您参考,该平台是一个 Azure Web 应用程序。

我确实有一个可行的解决方案,但缺点是必须添加到每条路线,这看起来很麻烦。

    [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 ...
    }

可以做一个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
        }
    }
}

您可以在 ControllerAction 级别使用

[RestrictVerbs("GET")]
public class VerbsController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

POST 到控制器中的任何操作:

第...