I am using MVC C#.
Can somebody give an example on why one would use
[HttpPost/HttpGet]
for an Action. How can an active have both - what is the practical use?
I am using MVC C#.
Can somebody give an example on why one would use
[HttpPost/HttpGet]
for an Action. How can an active have both - what is the practical use?
You cant combine this to attributes.
But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.
The
ActionName
Attribute allows to have 2 ActionMethods with the same name.In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution
You don't need to specify both at the same time, unless you're specifically restricting the other verbs (i.e. you don't want PUT or DELETE, etc).
Contrary to some of the comments, I was also unable to use both Attributes
[HttpGet, HttpPost]
at the same time, but was able to specify both verbs instead.Actions
Results
via POSTMAN, formatting by markdowntables
Let's say you have a
Login
action which provides the user with a login screen, then receives the user name and password back after the user submits the form:MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.
Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.
You can also combine the request method attributes if your action serves requests from multiple verbs:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
.