如何使用动作过滤器重定向MVC3中控制器动作的输出

Sam*_*tar 1 asp.net-mvc asp.net-mvc-3

我的代码中有以下内容:

if (Session["CurrentUrl"] != null) 
{
    var ip = new Uri((string)Session["CurrentUrl"]);
    var ipNoPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery);
    return Redirect(ipNoPort);
}

return Home();
Run Code Online (Sandbox Code Playgroud)

它检查是否设置了Session变量,然后重定向到该URL或让操作返回到Home方法.
有没有人有一个如何将其转换为动作过滤器的示例?
我也可以使用"Home"参数提供动作过滤器,以便知道下一步要去哪里?

gdo*_*ica 5

以下是重定向的ActionFilter示例

public class TheFilter: ActionFilterAttribute
{
   public override void OnActionExecuted(ActionExecutedContext filterContext)
   {
       var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
       if (controllerName !="TopSecert")
            return;

       var redirectTarget = new RouteValueDictionary
                 {{"action", "ActionName"}, {"controller", "ControllerName"}};

       filterContext.Result = new RedirectToRouteResult(redirectTarget);
       // Or give a url (the last in this example):
       filterContext = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsolutePath);
       // The session you can get from the context like that:
       var session = filterContext.HttpContext.Session;
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑:从执行更改为已执行并添加会话处理.