【问题标题】:Can I configure a controller to reject all Post methods?我可以将控制器配置为拒绝所有 Post 方法吗?
【发布时间】:2016-02-02 23:26:44
【问题描述】:

我们有一些只处理 GET 请求的控制器。当 POST 到达时,它会返回 500,而我宁愿返回 405(不允许的方法)。有没有办法设置它,以便控制器上的所有路由在收到 POST 时返回 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 ...
    }

【问题讨论】:

    标签: asp.net asp.net-mvc azure post asp.net-web-api2


    【解决方案1】:

    可以做一个MVCActionFilter(类似Web ApiSystem.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();
        }
    }
    

    发布到控制器中的任何操作:

    第...

    【讨论】:

    • 我知道至少有一种比剪切粘贴更好的方法!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2014-04-27
    相关资源
    最近更新 更多