我有一个具有相同签名的 GET 和 POST 方法,这会导致编译时错误。
[HttpGet]
public ActionResult MyAction(string myString)
{
// do some stuff
return View();
}
[HttpPost]
public ActionResult MyAction(string myOtherString)
{
// do different stuff
return View();
}
所以我必须在 Get 请求中对 myString 做一些事情,但我必须在 POST 请求中对 myOtherString 做一些其他事情。做一些研究我看到以下堆栈溢出答案 - post and get with same method signature
接受的答案是:
[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();
}
我的问题确实是 - 在已接受的答案中,对“SomeController”、“Friends”的 POST 请求是否仍会导致执行 Friends_Post 操作?
最佳答案
创建有效的操作方法有两个方面。 1) 路由框架必须能够区分并且 2) 首先它必须是可编译代码。
制作一个 GET 和一个 POST 满足第一个要求:路由框架将知道调用哪个操作。但是,从基本的 C# 角度来看,同一个类中仍然有两个具有相同签名的方法:名称、参数类型和计数以及返回值。如果您只更改其中一个因素,代码就可以编译。
最简单的方法,您实际上会在带有 CRUD 操作的脚手架 Controller 中看到它,是更改 POST 操作的名称,然后用 ActionName
属性修饰它以保持网址一样。正如我所说,带有 CRUD 操作的脚手架 Controller 使用以下示例:
public ActionResult Delete(int id)
{
...
}
[HttpPost]
[ActionName("Delete")]
public ActionResult DeleteConfirm(int id)
{
...
}
关于c# - MVC 中具有相同签名的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26530145/