MVC5中限制所有HTTP请求必须为POST

项目组老大给的一个应用场景,如何限制所有MVC接收到的HTTP请求必须是POST方式,经过查阅资料,最后总结了三种最为常见的方法:

一、在方法之前加标记

public class HomeController : Controller
{
[HttpPost]//在方法之前加标记,限制该方法只能为Post提交
public ActionResult Index()
{
return View();
}
}

二、通过路由限制

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
//限制请求方式必须是POST
constraints:new { httpMethod =  new HttpMethodConstraint("POST")}
);
}
}

三、写全局过滤器

public class HttpPostFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.IsPostMethod() == false) {

//如果不是POST请求,则返回404。
filterContext.Result = new HttpNotFoundResult();
}
}
}

注:需要在程序启动时注册上述过滤

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HttpPostFilter());
}
}

点击下载Demo
本文内容引用自 Sweet-Tang 博客园

 

THE END