我试图找出如何在我的MVC控制器操作中重用一些代码。如果设置了某个状态,我想重定向到另一个页面。我已经编写了一种方法来执行此操作,但似乎我必须将其粘贴到每个控制器操作中,例如。
[HttpGet]
public virtual ActionResult DoThis(Guid id)
ActionResult result;
if (checkRedirect(out result))
{
return result;
}
//otherwise continue
我以为我可以使用动作过滤器来做到这一点但是我必须在过滤器中设置属性注入以检查我想要避免的状态。必须有一种常见的方式来做到这一点我错过了吗?
答案 0 :(得分:2)
创建一个基本控制器并从中继承其他控制器:
public class DefaultController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ActionResult result;
if (checkRedirect(out result))
{
filterContext.Result = result; // redirect
}
}
}
并在您的控制器中:
public class SomeController : DefaultController
{
[HttpGet]
public virtual ActionResult DoThis(Gud)
{
// do something here which you were putting in else part
}
}
或创建动作过滤器属性:
public class MyCustomAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ActionResult result;
if (checkRedirect(out result))
{
filterContext.Result = result; // redirect
}
}
}
并将其付诸行动:
public class SomeController : Controller
{
[HttpGet]
[MyCustom]
public virtual ActionResult DoThis(Gud)
{
// do something here which you were putting in else part
}
}