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

How to restrict all HTTP requests to POST?

Jun 19, 2017 am 10:09 AM
http how limit

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does http status code 520 mean? What does http status code 520 mean? Oct 13, 2023 pm 03:11 PM

HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

How to remove comment restrictions on video accounts? What is the word limit for comments on a video account? How to remove comment restrictions on video accounts? What is the word limit for comments on a video account? Mar 22, 2024 pm 02:11 PM

With the popularity of video accounts on social media, more and more people are beginning to use video accounts to share their daily lives, insights and stories. However, some users may experience comments being restricted, which can leave them confused and dissatisfied. 1. How to remove comment restrictions on video accounts? To lift the restriction on commenting on a video account, you must first ensure that the account has been properly registered and real-name authentication has been completed. Video accounts have requirements for comments. Only accounts that have completed real-name authentication can lift comment restrictions. If there are any abnormalities in the account, these issues need to be resolved before comment restrictions can be lifted. 2. Comply with the community standards of the video account. Video accounts have certain standards for comment content. If the comment involves illegal content, you will be restricted from speaking. To lift comment restrictions, you need to abide by the community of the video account

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

http request 415 error solution http request 415 error solution Nov 14, 2023 am 10:49 AM

Solution: 1. Check the Content-Type in the request header; 2. Check the data format in the request body; 3. Use the appropriate encoding format; 4. Use the appropriate request method; 5. Check the server-side support.

How to use JavaScript to drag and zoom images while limiting them to the container? How to use JavaScript to drag and zoom images while limiting them to the container? Oct 20, 2023 pm 04:19 PM

How does JavaScript implement dragging and zooming of images while limiting them to the container? In web development, we often encounter the need to drag and zoom images. This article will introduce how to use JavaScript to implement dragging and zooming of images and limit operations within the container. 1. Drag the picture To drag the picture, we can use mouse events to track the mouse position and move the picture position accordingly. The following is a sample code: //Get the picture element varimage

What status code is returned for an HTTP request timeout? What status code is returned for an HTTP request timeout? Feb 18, 2024 pm 01:58 PM

The HTTP request times out, and the server often returns the 504GatewayTimeout status code. This status code indicates that when the server executes a request, it still fails to obtain the resources required for the request or complete the processing of the request after a period of time. It is a status code of the 5xx series, which indicates that the server has encountered a temporary problem or overload, resulting in the inability to correctly handle the client's request. In the HTTP protocol, various status codes have specific meanings and uses, and the 504 status code is used to indicate request timeout issues. in customer

How to implement HTTP streaming using C++? How to implement HTTP streaming using C++? May 31, 2024 am 11:06 AM

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.

See all articles