重定向到AuthorizeAttribute中的某个视图?

时间:2013-07-30 05:08:08

标签: asp.net-mvc custom-attributes authorize-attribute

在我的AdministratorController我有自定义属性的操作:

[AuthorizedOnly (Roles = "admin, superadmin")]
public ActionResult Index()
{...}

属性为:

class AuthorizedOnlyAttribute : AuthorizeAttribute
{
    public AuthorizedOnlyAttribute()
    {
        View = "~/Views/Main/Index.cshtml";
        Master = String.Empty;
    }
    public String View { get; set; }
    public String Master { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        CheckIfUserIsAuthenticated(filterContext);
    }
    private void CheckIfUserIsAuthenticated(AuthorizationContext filterContext)
    {
        if(filterContext.Result == null)
            return;
        if(filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            if(String.IsNullOrEmpty(View))
                return;
            var result = new ViewResult{ViewName = View, MasterName = Master};

            filterContext.Result = result;
        }
    }

它正确地向我显示了我需要的观点:~/Views/Main/Index.cshtml 但在我的浏览器中,URL仍然来自管理员控制器:.../Administrator/Index 如何重定向到我需要的视图,以便URL也会更改?

提前多多感谢!

1 个答案:

答案 0 :(得分:3)

试试这个

string retUrl = filterContext.HttpContext.Request.RawUrl;
filterContext.Result =
                 new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary 
                         {{ "controller", "Main" },
                          { "action", "Home" },
                          { "returnUrl",    retUrl } });