使用相同的方法签名发布和获取

使用相同的方法签名发布和获取

本文介绍了使用相同的方法签名发布和获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我有两个名为朋友"的操作.执行哪个取决于它是get"还是post".

In my controller I have two actions called "Friends". The one that executes depends on whether or not it's a "get" versus a "post".

所以我的代码片段看起来像这样:

So my code snippets look something like this:

// Get:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Friends()
{
    // do some stuff
    return View();
}

// Post:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Friends()
{
    // do some stuff
    return View();
}

然而,这不会编译,因为我有两个具有相同签名的方法(朋友).我该如何去创造这个?我是否只需要创建一个操作,但在其中区分获取"和发布"?如果是这样,我该怎么做?

However, this does not compile since I have two methods with the same signature (Friends). How do I go about creating this? Do I need to create just one action but differentiate between a "get" and "post" inside of it? If so, how do I do that?

推荐答案

将第二种方法重命名为Friends_Post"之类的其他名称,然后您可以将 [ActionName("Friends")] 属性添加到第二个.因此,请求类型为 POST 的 Friend 操作的请求将由该操作处理.

Rename the second method to something else like "Friends_Post" and then you can add [ActionName("Friends")] attribute to the second one. So the requests to the Friend action with POST as request type, will be handled by that action.

// Get:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Friends()
{
    // do some stuff
    return View();
}

// Post:
[ActionName("Friends")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Friends_Post()
{
    // do some stuff
    return View();
}

这篇关于使用相同的方法签名发布和获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:21