【发布时间】:2015-03-25 13:27:14
【问题描述】:
我有一个关于 ASP.NET MVC 中 ActionResult 行为的简单问题。
我需要有两个名称相同但参数不同的操作结果。 我特别想要这个:
public class CarController : Controller
{
[AuthorizeUser(AccessLevel = "New")]
public ActionResult New()
{
return View("New");
}
[AuthorizeUser(AccessLevel = "New?type=2")]
public ActionResult New(string type)
{
return View("NewCarType2");
}
}
我知道我可以用不同的名称重命名第二个操作结果,但如果我想将其保留为“新”?
我尝试使用 route.maps 没有成功。 我想这样做:
public class CarController : Controller
{
public ActionResult New (string type) {
if(!string.IsNullOrEmpty(type) && type.Equals("2")) {
return NewCarType2()
else
return New()
}
}
[AuthorizeUser(AccessLevel = "New?type=2")]
private ActionResult NewCarType2()
{
return View("NewCarType2");
}
[AuthorizeUser(AccessLevel = "New")]
private ActionResult New()
{
return View("New");
}
}
但用户授权的属性被忽略.. 方法的签名也是 public 和属性 [NoAction]。
我发现做我想做的事情的唯一方法是使用类继承:
public class CarController : Controller
{
public virtual ActionResult New(string type)
{
if (!string.IsNullOrEmpty(type) && type.Equals("2"))
return RedirectToAction("NewCarType2", "CarOverride");
else
return RedirectToAction("New", "CarOverride");
}
}
public class CarOverrideController : CarController
{
[AuthorizeUser(AccessLevel = "New?type=2")]
public ActionResult NewCarType2(string type)
{
return View("NewCarType2");
}
[AuthorizeUser(AccessLevel = "New")]
public override ActionResult New(string type)
{
return View("New");
}
}
但是这是处理这种情况的正确方法吗(ActionResults 的名称部分写的都不同)?
【问题讨论】:
-
其实这就是方法重载的概念stackoverflow.com/a/436935/3354492这个帖子会回答你的问题。
-
另一种管理方法是将一个定义为 [HttpGet] 操作,另一个定义为 [HttpPost] 操作 注意:不确定这是您想要的,但它可以这样工作(无论如何,参数必须不同)
-
绝对建议不要在这里使用继承
-
您的 AuthorizeUser 属性执行什么逻辑?
-
@timothyclifford 与 AuthorizeUser 属性我检查用户的角色以及他是否有权显示页面(使用 IsInRole 方法)
标签: c# asp.net asp.net-mvc asp.net-mvc-4 actionresult