MVC 5 limits all HTTP requests to be POST, mvcpost

Source: Internet
Author: User

MVC 5 limits all HTTP requests to be POST, mvcpost

Today, a colleague raised the following question: He wants to restrict all HTTP requests received by mvc to the post method.

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

I. HttpPostAttribute features

First of all, MVC provides the HttpPostAttribute feature, which is used to restrict the submission of HTTP requests in POST mode.

public class HomeController : Controller {  [HttpPost] public ActionResult Index() {  return View(); } }

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

//// Abstract: // indicates a feature used to restrict operation methods so that the method can only process http post requests. [AttributeUsage (AttributeTargets. Method, AllowMultiple = false, Inherited = true)] public sealed class httppostattriage: ActionMethodSelectorAttribute {}

Ii. Use HttpModule

In the Asp. Net pipeline, you can use HttpModule to register your own event handlers for events in the HttpApplication object to control all HTTP requests.

Public class HttpMethodModule: IHttpModule {public void Init (HttpApplication context) {context. postMapRequestHandler + = Context_PostMapRequestHandler;} private void Context_PostMapRequestHandler (object sender, EventArgs e) {HttpApplication httpApplication = (HttpApplication) sender; HttpContext httpContext = httpApplication. context; // determine whether the MVC framework is used to process requests. Other requests are not controlled. MvcHandler mvcHandler = httpContext. Handler as MvcHandler; if (mvcHandler! = Null & httpContext. IsPostMethod () = false) {throw new HttpException (404, "the accessed resource does not exist. ") ;}} Public void Dispose (){}}

Add related configurations in Web. config.

<?xml version="1.0" encoding="utf-8"?><configuration> <system.webServer> <modules> <add name="HttpMethod" type="HttpPostWebApp.Web.HttpMethodModule, HttpPostWebApp"/> </modules> </system.webServer></configuration>

After testing, we can meet our requirements (the test results are not demonstrated ).

Iii. MVC Filter

In MVC, you can use global filters to control requests.

Public class HttpPostFilter: IAuthorizationFilter {public void OnAuthorization (AuthorizationContext filterContext) {if (filterContext. HttpContext. IsPostMethod () = false) {// if it is not a POST request, 404 is returned. FilterContext. Result = new HttpNotFoundResult ();}}}

Register as a global filter when the program starts.

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

Iv. Routing Constraints

When registering a route, you can define the routing constraints. Use the following method to restrict the request method to post requests.

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} // The request method must be POST, constraints: new {httpMethod = new HttpMethodConstraint ("POST ")});}}

5. Rewrite the Controller Method

In MVC, All controllers are inherited from controllers by default.

We can define an abstract class of BaseController and rewrite OnActionExecuting. Other controllers are inherited from BaseController.

Public abstract class BaseController: Controller {protected override void OnActionExecuting (ActionExecutingContext filterContext) {if (filterContext. httpContext. isPostMethod () = false) {// if the request is not a POST request, 404 is returned. FilterContext. Result = new HttpNotFoundResult () ;}else {base. OnActionExecuting (filterContext );}}}

This method requires modifying the base classes of All controllers. It is not recommended.

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

Summary

Among the above five methods, method 2, method 3, and method 4 are very simple, but I recommend method 4, because if the demand changes, the maintenance workload is minimal.

If you have other methods, please leave a message. Thank you!

Demo download: mvchttppostwebapp

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.