且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC [HttpPost/HttpGet] 用于操作

更新时间:2022-11-27 21:56:26

假设您有一个 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)].