asp.net-mvc MVC [HttpPost/HttpGet] 用于操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11767911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:08:58  来源:igfitidea点击:

MVC [HttpPost/HttpGet] for Action

asp.net-mvcmodel-view-controller

提问by Nate Pet

I am using MVC C#.

我正在使用 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?

为一个动作。一个主动怎么能两者兼得——实际用途是什么?

回答by Jesse Hallam

Let's say you have a Loginaction which provides the user with a login screen, then receives the user name and password back after the user submits the form:

假设您有一个Login操作为用户提供登录屏幕,然后在用户提交表单后接收用户名和密码:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

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.

MVC 没有得到关于哪个动作是哪个动作的明确说明,即使我们可以通过查看它来判断。如果将 [HttpGet] 添加到第一个操作,将 [HttpPost] 添加到部分操作,MVC 清楚地知道哪个操作是哪个。

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.

为什么?请参阅请求方法。长和短:当用户查看页面时,这是一个 GET 请求,而当用户提交一个表单时,这通常是一个 POST 请求。HttpGet 和 HttpPost 只是将操作限制为适用的请求类型。

[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)].

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

回答by drzaus

You don't need to specify both at the same time, unless you're specifically restricting the otherverbs (i.e. you don't want PUT or DELETE, etc).

您不需要同时指定两者,除非您特别限制其他动词(即您不想要 PUT 或 DELETE 等)。

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.

与一些评论相反,我也无法同时使用这两个属性[HttpGet, HttpPost],但能够指定两个动词。

Actions

行动

    private ActionResult testResult(int id)
    {
        return Json(new {
                            // user input
                            input = id,
                            // just so there's different content in the response
                            when = DateTime.Now,
                            // type of request
                            req = this.Request.HttpMethod,
                            // differentiate calls in response, for matching up
                            call = new StackTrace().GetFrame(1).GetMethod().Name
                        },
                        JsonRequestBehavior.AllowGet);
    }
    public ActionResult Test(int id)
    {
        return testResult(id);
    }
    [HttpGet]
    public ActionResult TestGetOnly(int id)
    {
        return testResult(id);
    }
    [HttpPost]
    public ActionResult TestPostOnly(int id)
    {
        return testResult(id);
    }
    [HttpPost, HttpGet]
    public ActionResult TestBoth(int id)
    {
        return testResult(id);
    }
    [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
    public ActionResult TestVerbs(int id)
    {
        return testResult(id);
    }

Results

结果

via POSTMAN, formatting by markdowntables

通过邮递员,按markdowntables格式化

| Method    | URL                   | Response                                                                                  |
|--------   |---------------------- |----------------------------------------------------------------------------------------   |
| GET       | /ctrl/test/5          | { "input": 5, "when": "/Date(1408041216116)/", "req": "GET", "call": "Test" }             |
| POST      | /ctrl/test/5          | { "input": 5, "when": "/Date(1408041227561)/", "req": "POST", "call": "Test" }            |
| PUT       | /ctrl/test/5          | { "input": 5, "when": "/Date(1408041252646)/", "req": "PUT", "call": "Test" }             |
| GET       | /ctrl/testgetonly/5   | { "input": 5, "when": "/Date(1408041335907)/", "req": "GET", "call": "TestGetOnly" }      |
| POST      | /ctrl/testgetonly/5   | 404                                                                                       |
| PUT       | /ctrl/testgetonly/5   | 404                                                                                       |
| GET       | /ctrl/TestPostOnly/5  | 404                                                                                       |
| POST      | /ctrl/TestPostOnly/5  | { "input": 5, "when": "/Date(1408041464096)/", "req": "POST", "call": "TestPostOnly" }    |
| PUT       | /ctrl/TestPostOnly/5  | 404                                                                                       |
| GET       | /ctrl/TestBoth/5      | 404                                                                                       |
| POST      | /ctrl/TestBoth/5      | 404                                                                                       |
| PUT       | /ctrl/TestBoth/5      | 404                                                                                       |
| GET       | /ctrl/TestVerbs/5     | { "input": 5, "when": "/Date(1408041709606)/", "req": "GET", "call": "TestVerbs" }        |
| POST      | /ctrl/TestVerbs/5     | { "input": 5, "when": "/Date(1408041831549)/", "req": "POST", "call": "TestVerbs" }       |
| PUT       | /ctrl/TestVerbs/5     | 404                                                                                       |

回答by Ben Anderson

In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution

在 Mvc 4 中你可以使用 AcceptVerbsAttribute,我认为这是一个非常干净的解决方案

[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
   // Login logic
}

回答by dknaack

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 ActionNameAttribute allows to have 2 ActionMethods with the same name.

ActionName属性允许有 2 个同名的 ActionMethods。

[HttpGet]
public ActionResult MyMethod()
{
    return MyMethodHandler();
}

[HttpPost]
[ActionName("MyMethod")]
public ActionResult MyMethodPost()
{
    return MyMethodHandler();
}

private ActionResult MyMethodHandler()
{
    // handle the get or post request
    return View("MyMethod");
}