asp.net-mvc - 如何让过滤器重定向到另一个操作?

标签 asp.net-mvc redirecttoaction

RedirectToAction 是 protected ,我们只能在操作中使用它。但如果我想在过滤器中重定向?

public class IsGuestAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!Ctx.User.IsGuest) 
            filterContext.Result = (filterContext.Controller as Controller)
                .RedirectToAction("Index", "Home");
    }
}

最佳答案

RedirectToAction 只是构造 RedirectToRouteResult() 的辅助方法,因此您只需创建一个新的 RedirectToRouteResult() 传递沿着带有您的操作值的 RouteValueDictionary()

基于下面评论中@Domenic 的代码的完整示例:

public class IsGuestAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!Ctx.User.IsGuest) 
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary 
                { 
                    { "controller", "Home" }, 
                    { "action", "Index" } 
                });
        }
    }
}

关于asp.net-mvc - 如何让过滤器重定向到另一个操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/550995/

相关文章:

asp.net-mvc - 重定向到另一个 Controller 中的操作

c# - ASP.NET MVC RedirectToAction 未重定向到另一个 Controller 的索引

javascript - 如何追加部分 View 的根元素

asp.net-mvc - Grid.Mvc 缺少文档

c# - asp.net mvc 模型绑定(bind)不绑定(bind)集合

c# - 服务层应该保留任何状态吗?或者仅通过构造函数/ setter 注入(inject)?

c# - 在 Web API 中使用 RedirectToAction

asp.net-mvc - 将 View 数据保留在 RedirectToAction 上

asp.net-mvc - ASP.NET MVC 3 内存中数据存储

ruby-on-rails - Redirect_to 从设计创建到模型创建 - 使用帮助程序 - 语法错误