MVC 5 limit all HTTP requests must be post mode

Source: Internet
Author: User
Tags http post
Today, a colleague raised the question that he wanted to limit the HTTP requests received by all MVC to be post.

Next in the content below, will I think of the way to share to everyone, if you have other ways, please leave a message.

First, Httppostattribute characteristics

First of all, when you think of it, MVC provides the Httppostattribute feature, which is used to restrict HTTP requests that must be post-submitted.

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, do a coder, this way, we certainly can not receive.

1     //2     //Abstract: 3     //     represents an attribute that is used to restrict the action method so that the method only processes HTTP POST requests. 4     [AttributeUsage (AttributeTargets.Method, AllowMultiple = False, inherited = True)]5 public     sealed class Httppostattribute:actionmethodselectorattribute6     {7 8     }
View Code

Second, the use of HttpModule

In an ASP. NET pipeline, you can control all HTTP requests by registering your own event handlers for the events in the HttpApplication object by HttpModule.

1 Public     class Httpmethodmodule:ihttpmodule 2     {3 public         void Init (HttpApplication context) 4         {5             C Ontext. Postmaprequesthandler + = Context_postmaprequesthandler; 6         } 7  8         private void Context_postmaprequesthandler (object sender, EventArgs e) 9         {Ten             HttpApplication HttpApplication = (HttpApplication) sender;11             httpcontext httpcontext = HttpApplication.Context;             to determine whether the MVC framework is currently being used to process requests, other instructions do not control.             Mvchandler Mvchandler = Httpcontext.handler as mvchandler;16             if (mvchandler! = null && Httpcontex T.ispostmethod () = = False) {$                 throw new HttpException (404, "The resource accessed does not exist. ");             }20         }21 public         void Dispose () at $         }26     }

Add the related configuration 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 is possible to meet our requirements (the test results are not done in the demo).

Third, MVC filter

In MVC, the request can be controlled by a global filter.

1 Public     class Httppostfilter:iauthorizationfilter 2     {3 public         void Onauthorization ( AuthorizationContext filtercontext) 4         {5             if (filterContext.HttpContext.IsPostMethod () = = False) {6  7                 //If it is not a POST request, 404 is returned. 8                 Filtercontext.result = new Httpnotfoundresult (); 9             }10         }11     }

When the program starts, it is registered as a global filter.

1 public     class FilterConfig2     {3 public         static void Registerglobalfilters (Globalfiltercollection filters) 4         {5             filters. ADD (New Httppostfilter ()); 6         }7     }

IV. Routing constraints

When you register a route, you can define a constraint for the route. You can limit the request mode to a POST request in the following ways.

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", a ction = "Index", id = urlparameter.optional} 9                 //Limit request method must be POST10               , constraints:new {httpmethod =  new Http Methodconstraint ("POST")}11             );         }13     }

V. Rewriting the Controller method

In MVC, all controllers inherit from the controller by default.

We can define an abstract class of Basecontroller, rewrite the onactionexecuting, and all 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                 //If it is not a POST request, 404 is returned. 8                 Filtercontext.result = new Httpnotfoundresult (); 9             }10             else {one                 base. OnActionExecuting (Filtercontext);             }13         }14     }

This method requires modifying the base class of all controllers, not recommended.

Of course, if you have defined your own controller base class, this is a very small amount of work.

Summarize

Of the above five methods, the two, three or four methods are very simple, but I recommend method four, because if the requirements change, the maintenance workload is minimal.

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.