MVC [HttpPost/HttpGet] 用于操作 [英] MVC [HttpPost/HttpGet] for Action
问题描述
我使用的是 MVC C#.
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?
推荐答案
假设您有一个 Login
操作,它为用户提供一个登录屏幕,然后在登录后接收用户名和密码用户提交表单:
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:
public ActionResult Login() {
return View();
}
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
MVC 没有得到关于哪个动作是哪个动作的明确说明,即使我们可以通过查看它来判断.如果将 [HttpGet] 添加到第一个操作,将 [HttpPost] 添加到部分操作,MVC 清楚地知道哪个操作是哪个.
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.
为什么?请参阅请求方法.长和短:当用户查看页面时,这是一个 GET 请求,而当用户提交一个表单时,这通常是一个 POST 请求.HttpGet 和 HttpPost 只是将操作限制为适用的请求类型.
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.
[HttpGet]
public ActionResult Login() {
return View();
}
[HttpPost]
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
如果您的操作服务于来自多个动词的请求,您还可以组合请求方法属性:
You can also combine the request method attributes if your action serves requests from multiple verbs:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
.
这篇关于MVC [HttpPost/HttpGet] 用于操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!