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(); } }
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 { }
2. Using HttpModule
In the Asp.Net pipeline, you can use HttpModule to handle events in the HttpApplication object Register your own event handler 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() { } }
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>
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(); } } }
When the program starts, register as a global filter.
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HttpPostFilter()); } }
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.
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")} ); } }
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); } } }
This method requires modifying the base classes of all controllers and 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, 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!
The above is the detailed content of MVC5 restricts all HTTP requests to POST. For more information, please follow other related articles on the PHP Chinese website!

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
