17

在我的应用程序中,我想重定向授权用户以更新他们的个人资料页面,直到他们提供了所需的信息。如果他们更新配置文件,则IsProfileCompleted在数据库中将其设置为“true”。

所以,我知道这可以通过将检查条件放入控制器所需的操作中来完成。但我想通过自定义AuthorizeAttribute.

我用谷歌搜索并“StackOverflowed”获取信息,但感到困惑。请指导我。

4

2 回答 2

44
public class MyAuthorizeAttribute: AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // The user is not authorized => no need to go any further
            return false;
        }

        // We have an authenticated user, let's get his username
        string authenticatedUser = httpContext.User.Identity.Name;

        // and check if he has completed his profile
        if (!this.IsProfileCompleted(authenticatedUser))
        {
            // we store some key into the current HttpContext so that 
            // the HandleUnauthorizedRequest method would know whether it
            // should redirect to the Login or CompleteProfile page
            httpContext.Items["redirectToCompleteProfile"] = true;
            return false;
        }

        return true;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile"))
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "someController",
                action = "someAction",
            });
            filterContext.Result = new RedirectToRouteResult(routeValues);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }

    private bool IsProfileCompleted(string user)
    {
        // You know what to do here => go hit your database to verify if the
        // current user has already completed his profile by checking
        // the corresponding field
        throw new NotImplementedException();
    }
}

然后你可以用这个自定义属性来装饰你的控制器动作:

[MyAuthorize]
public ActionResult FooBar()
{
    ...
}
于 2013-10-14T11:12:58.197 回答
0

我采用了这段代码并添加了一些我自己的更改,即检查当前登录的用户是否在服务器上具有会话状态,它们不像以前那么昂贵!

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized && !Membership.isAuthenticated())
        {
            // The user is not authorized => no need to go any further
            return false;
        }

        return true;
    }
}
public class Membership
{
    public static SystemUserDTO GetCurrentUser()
    {
        // create a system user instance
        SystemUserDTO user = null;

        try
        {
            user = (SystemUserDTO)HttpContext.Current.Session["CurrentUser"];
        }
        catch (Exception ex)
        {
            // stores message into an event log
            Utilities.Log(ex.Message, System.Diagnostics.EventLogEntryType.Warning);

        }
        return user;
    }

    public static bool isAuthenticated()
    {
        bool loggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
        bool hasSession = (GetCurrentUser() != null);
        return (loggedIn && hasSession);
    }
}
于 2014-11-25T12:55:47.697 回答