Home > Backend Development > C#.Net Tutorial > How to restrict all HTTP requests to POST?

How to restrict all HTTP requests to POST?

零下一度
Release: 2017-06-19 10:09:20
Original
2985 people have browsed it

This article mainly introduces in detail the method of MVC 5 to restrict all HTTP requests to be POST. It has certain reference value. Interested friends can refer to it.

There is a colleague today , raised such a question, he wanted to restrict all HTTP requests received by MVC to be in POST mode.

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.


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

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. .


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

 }
Copy after login

2. Using HttpModule

In the Asp.Net pipeline, you can use HttpModule to handle events in the HttpApplication object Register your own Event handler program 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;


  //判断当前是否使用的是 MVC 框架来处理请求,其它的请示不做控制。
  MvcHandler mvcHandler = httpContext.Handler as MvcHandler;

  if (mvcHandler != null && httpContext.IsPostMethod() == false) {
  throw new HttpException(404, "访问的资源不存在。");
  }
 }

 public void Dispose()
 {

 }
 }
Copy after login

Add relevant 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>
Copy after login

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.


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

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

When the program starts, register as a global filter.


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

4. Routing constraints

When registering a route, you candefine the route constraint. In the following way, the request method can be limited 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 }
  //限制请求方式必须是POST
  , constraints:new { httpMethod = new HttpMethodConstraint("POST")}
  );
 }
 }
Copy after login

5. Override 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.


public abstract class BaseController : Controller
 {
 protected override void OnActionExecuting(ActionExecutingContext filterContext)
 {
  
  if (filterContext.HttpContext.IsPostMethod() == false) {
  //如果不是POST请求,则返回404。
  filterContext.Result = new HttpNotFoundResult();
  }
  else {
  base.OnActionExecuting(filterContext);
  }
 }
 }
Copy after login

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, the second, third, and fourth methods are very simple, but I recommend the fourth method, because if the needs change , the maintenance workload is minimal.

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

Demo download:mvchttppostwebapp

The above is the detailed content of How to restrict all HTTP requests to POST?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template