Met*_*uru 178 c# asp.net-mvc onactionexecuting
我尝试了两种方法:Response.Redirect(),它什么都不做,以及在基本控制器内部调用一个返回ActionResult并让它返回RedirectToAction()的新方法......这两种方法都不起作用.
如何从OnActionExecuting方法进行重定向?
wom*_*omp 353
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
...
if (needToRedirect)
{
...
filterContext.Result = new RedirectResult(url);
return;
}
...
}
Run Code Online (Sandbox Code Playgroud)
Ran*_*den 53
它也可以这样做:
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{"controller", "Home"},
{"action", "Index"}
}
);
Run Code Online (Sandbox Code Playgroud)
K.K*_*nan 35
创建一个单独的类,
public class RedirectingAction : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
if (CheckUrCondition)
{
context.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Home",
action = "Index"
}));
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在创建控制器时,将此注释称为
[RedirectingAction]
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果重定向的控制器继承自baseController我们重写OnActionExecuting方法的相同位置,则会导致递归循环。假设我们将其重定向到帐户控制器的登录操作,那么登录操作将调用OnActionExecuting方法并一次又一次地重定向到相同的登录操作
...因此,我们应该应用一种签入OnActionExecuting方法来检查请求是否来自同一控制器,如果是,则不要再次重定向其登录操作。这是代码:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
// some condition ...
}
catch
{
if (filterContext.Controller.GetType() != typeof(AccountController))
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
{ "controller", "Account" },
{ "action", "Login" }
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88682 次 |
| 最近记录: |