在同一个Controller中具有相同Action名称的GET和POST方法

Ric*_*olo 76 c# asp.net-mvc asp.net-mvc-3

为什么这不正确?

{
    public class HomeController : Controller
    {

        [HttpGet]
        public ActionResult Index()
        {
            Some Code--Some Code---Some Code
            return View();
        }

        [HttpPost]
        public ActionResult Index()
        {
            Some Code--Some Code---Some Code
            return View();
        }

    }
Run Code Online (Sandbox Code Playgroud)

我怎样才能让控制器在"getted"时回答一件事,在"发布"时回答一件事?

Bro*_*ass 163

由于您不能使用具有相同名称和签名的两个方法,因此必须使用该ActionName属性:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}
Run Code Online (Sandbox Code Playgroud)

另请参阅"方法如何成为行动"


小智 36

虽然ASP.NET MVC允许您使用相同名称的两个操作,但.NET不允许您使用相同签名的两个方法 - 即相同的名称和参数.

您需要以不同的方式命名方法,使用ActionName属性告诉ASP.NET MVC它们实际上是相同的操作.

也就是说,如果您正在谈论GET和POST,这个问题可能会消失,因为POST操作将采用比GET更多的参数,因此可以区分.

所以,你需要:

[HttpGet]
public ActionResult ActionName() {...}

[HttpPost, ActionName("ActionName")]
public ActionResult ActionNamePost() {...}
Run Code Online (Sandbox Code Playgroud)

要么,

[HttpGet]
public ActionResult ActionName() {...}

[HttpPost]
public ActionResult ActionName(string aParameter) {...}
Run Code Online (Sandbox Code Playgroud)


joc*_*ull 16

我喜欢接受我的POST动作的表格帖子,即使我不需要它.对我来说,感觉就像你应该发布的东西一样正确.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //Code...
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 唯一的问题是,即使 [AllowHtml] 等,这也会触发严重的 HttpRequestValidationException。并不是说这是一个糟糕的异常,而是它的实现以及它何时被触发(特别是当它在某个区域中被触发时)不必要地不透明。 (2认同)

Jef*_*ver 5

要回答您的具体问题,您不能在一个类中使用两个具有相同名称和相同参数的方法; 使用HttpGet和HttpPost属性不区分方法.

为了解决这个问题,我通常会为您发布的表单添加视图模型:

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        Some Code--Some Code---Some Code
        return View();
    }

    [HttpPost]
    public ActionResult Index(formViewModel model)
    {
        do work on model --
        return View();
    }

}
Run Code Online (Sandbox Code Playgroud)


Rre*_*Cat 5

您收到了这个问题的很好答案,但我想补充两点。您可以使用一种方法并根据请求类型处理请求:

public ActionResult Index()
{
    if("GET"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for GET
    }
    else if("POST"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for POST
    }
    else
    {
        //exception
    }

    return View();
}
Run Code Online (Sandbox Code Playgroud)