So we have [HttpPost], which is an optional attribute. I understand this restricts the call so it can only be made by an HTTP POST request. My question is why would I want to do this?
相关问题
- MVC-Routing,Why i can not ignore defaults,The matc
- Custom Attribute to Process info before a method i
- parameters in routing do not work MVC 3
- There is no ViewData item with the key 'taskTy
- What can be the maximum “POST” size I can have?
相关文章
- How to get a list of connected clients on SignalR
- How do you redirect to the calling page in ASP.NET
- Change color of bars depending on value in Highcha
- The program '[4432] iisexpress.exe' has ex
- Show a different value from an input that what wil
- ASP.Net MVC 4 Bundles
- How to get server path of physical path ?
- Cannot implicitly convert Web.Http.Results.JsonRes
This is mainly so that you can have two Actions with the same name, one which is used on GETs and perhaps displays a form for user entry and the other being used on POSTs when the user submits the form displayed by the original GET. If the Actions are not differentiated in this way, an error will occur due to being unable to resolve which Action is intended to handle the request.
As far as best practices for HttpGet and HttpPost, it is good practice in any web development to use HttpPost for Creates, Updates, and Deletes (data modification). Post are good, because they require a form submission, which prevents users from clicking poisoned links(e.g. [https://www.mysite.com/Delete/1]) in emails, social sites, etc. and changing data inadvertently. If you are basically just Reading data HttpGet works great.
See OWASP for more in-depth security considerations and why the validation token increases security.
Imagine the following:
This wouldn't be possible unless the ActionMethodSelectorAttributes
HttpGet
andHttpPost
where used. This makes it really simple to create an edit view. All the action links just points right back to the controller. If the view model validates false, you just pop right back to the edit view again.I will be bold and say this is best practice when it comes to CRUDish things in ASP.NET MVC.
EDIT:
@TheLight asked what was needed in the view to accomplish the post. It's simply just a form with method POST.
Using Razor, this would look something like this.
This renders the following HTML:
When the form is submitted, it will perform an Http Post request to the controller. The action with the
HttpPost
attribute will handle the request.Its so you can have multiple Actions that use the same name, you can use the HttpPost attribute to mark which method gets handled on a Post request like so: