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

时间:2016-02-02 23:26:44

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

我们有一些控制器,它们只希望处理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 ...
    }

1 个答案:

答案 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:

Request inspection

Hth...