授权属性中的UrlHelper和ViewContext

DM.*_*DM. 7 asp.net asp.net-mvc asp.net-membership custom-attributes httpcontext

我有一个我无法解决的场景:

我正在为mvc创建自己的自定义授权属性.我想添加的主要功能是能够更改用户重定向的位置(如果用户不在某个角色中).我不介意系统发送他们回到登录页面,如果他们没有通过身份验证,但我想选择在那里给他们,如果他们进行身份验证,但不允许访问该操作方法.

这是我想做的事情:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
        public string Action;
        public string Controller;

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            // if User is authenticated but not in the correct role
            string url = Url.Action(this.Action, this.Controller);                
            httpContext.Response.Redirect(url);
        }
    }
Run Code Online (Sandbox Code Playgroud)

作为一个额外的奖励,我想在进行重定向之前访问ViewContext和TempData.

有关如何在属性中实例化UrlHelper和ViewContext的任何想法?

Dar*_*rov 11

您可以覆盖该OnAuthorization方法:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }

    // Call the AuthorizeCore which should return true or false
    if (!this.AuthorizeCore(filterContext.HttpContext))
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary()
        {
            { "controller", "home" },
            { "action", "about" },
            { "id", "foo" },
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

就ViewData和TempData而言:filterContext.Controller.ViewData并且filterContext.Controller.TempData应该在OnAuthorization方法内部工作.最后,如果你想使用UrlHelper(在这种情况下没有必要因为RedirectToRouteResult更好)你可以实例化它:

var urlHelper = new UrlHelper(filterContext.RequestContext);
Run Code Online (Sandbox Code Playgroud)