Home >Backend Development >C#.Net Tutorial >MVC 5 restricts all HTTP requests to be POST

MVC 5 restricts all HTTP requests to be POST

巴扎黑
巴扎黑Original
2017-06-26 15:20:012076browse

Today a colleague raised such a question. He wanted to restrict all HTTP requests received by MVC to be POST.

Next, in the following content, I will share with you the method I thought of. If you have other methods, please leave a message.

1. HttpPostAttribute feature

The first thing everyone thinks of is that MVC provides the HttpPostAttribute feature, which is used to restrict HTTP requests to be submitted in POST mode.

1   public class HomeController : Controller2   {        
3         [HttpPost]4         public ActionResult Index()5         {6             return View();7         }8   }

This feature can only be marked on the Action method. We need to mark each Action method and make a Coder. We definitely cannot accept this method.

1     //2     // 摘要:3     //     表示一个特性,该特性用于限制操作方法,以便该方法仅处理 HTTP POST 请求。4     [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]5     public sealed class HttpPostAttribute : ActionMethodSelectorAttribute6     {7 8     }
View Code

2. Using HttpModule

In the Asp.Net pipeline, you can Register your own event handler for events in the HttpApplication object through HttpModule to control all HTTP requests.

 1     public class HttpMethodModule : IHttpModule 2     { 3         public void Init(HttpApplication context) 4         { 5             context.PostMapRequestHandler += Context_PostMapRequestHandler; 6         } 7  8         private void Context_PostMapRequestHandler(object sender, EventArgs e) 9         {10             HttpApplication httpApplication = (HttpApplication) sender;11             HttpContext httpContext = httpApplication.Context;12 13 14             //判断当前是否使用的是 MVC 框架来处理请求,其它的请示不做控制。15             MvcHandler mvcHandler = httpContext.Handler as MvcHandler;16 17             if (mvcHandler != null && httpContext.IsPostMethod() == false) {18                 throw new HttpException(404, "访问的资源不存在。");19             }20         }21 22         public void Dispose()23         {24 25         }26     }

Add relevant configurations in Web.config.

1 <?xml version="1.0" encoding="utf-8"?>2 <configuration>3   <system.webServer>4     <modules>5       <add name="HttpMethod" type="HttpPostWebApp.Web.HttpMethodModule, HttpPostWebApp"/>6     </modules>7   </system.webServer>8 </configuration>

After testing, it can meet our requirements (the test results will not be demonstrated).

3. MVC filter

In MVC, requests can be controlled through global filters.

 1     public class HttpPostFilter : IAuthorizationFilter 2     { 3         public void OnAuthorization(AuthorizationContext filterContext) 4         { 5             if (filterContext.HttpContext.IsPostMethod() == false) { 6  7                 //如果不是POST请求,则返回404。 8                 filterContext.Result = new HttpNotFoundResult(); 9             }10         }11     }

When the program starts, register as a global filter.

1     public class FilterConfig2     {3         public static void RegisterGlobalFilters(GlobalFilterCollection filters)4         {5             filters.Add(new HttpPostFilter());6         }7     }

4. Routing constraints

When registering a route, you can define routing constraints. In the following way, the request method can be limited to POST requests.

 1     public class RouteConfig 2     { 3         public static void RegisterRoutes(RouteCollection routes) 4         { 5             routes.MapRoute( 6                 name: "Default", 7                 url: "{controller}/{action}/{id}", 8                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 9                 //限制请求方式必须是POST10               , constraints:new { httpMethod =  new HttpMethodConstraint("POST")}11             );12         }13     }

5. Overriding Controller methods

In MVC, all controllers inherit from Controller by default.

We can define an abstract class of BaseController, override OnActionExecuting, and other controllers inherit from BaseController.

 1     public abstract class BaseController : Controller 2     { 3         protected override void OnActionExecuting(ActionExecutingContext filterContext) 4         { 5              6             if (filterContext.HttpContext.IsPostMethod() == false) { 7                 //如果不是POST请求,则返回404。 8                 filterContext.Result = new HttpNotFoundResult(); 9             }10             else {11                 base.OnActionExecuting(filterContext);12             }13         }14     }

This method requires modifying the base classes of all controllers and is not recommended.

Of course, if you have already defined your own controller base class, the workload of this method is also very small.

Summary

Among the above five methods, methods two, three, and four are very simple, but I prefer method four, because if the requirements change, the maintenance workload is minimal.

If you have other methods, please leave a message, thank you!

The above is the detailed content of MVC 5 restricts all HTTP requests to be POST. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn