ASP.Net MVC 3首次登录/完成配置文件

本文关键字:配置文件 登录 Net MVC 3首 ASP | 更新日期: 2023-09-27 18:10:24

我使用FormsAuthenticationService和AccountMembershipService来处理会员资格和登录。我需要一种方法来强制用户在登录到站点时完成他们的配置文件,或者在能够继续访问站点之前转到需要[Authorize()]的区域。

我正在考虑在AuthorizationContext上使用GlobalFilter,但不确定这是否会按需要工作。

任何想法?

ASP.Net MVC 3首次登录/完成配置文件

经过一番挖掘,我终于找到了实现这一目标的方法。

首先创建一个全局过滤器

using System.Web.Mvc;
using Microsoft.Practices.Unity;
public sealed class LogOnAuthorize :  AuthorizeAttribute
{
[Dependency]
public Service.IDaoService dao { get; set; }

public override void OnAuthorization(AuthorizationContext filterContext)
{
    string SessionKey = "ProfileCompleted";
    bool Authorization = filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), true)
        || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), true);
    bool ContainsIgnore = filterContext.ActionDescriptor.IsDefined(typeof(IgnoreCompleteProfileAttribute), true)
        || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(IgnoreCompleteProfileAttribute), true);
    if ((Authorization) && (!ContainsIgnore))
    {
        var ctx = System.Web.HttpContext.Current;
        if (ctx != null)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated) 
            {
                if (ctx.Session[SessionKey] == null)
                {
                    Models.UserDetail user = dao.UserDao.GetByEmail(filterContext.HttpContext.User.Identity.Name);
                    if (user != null)
                        ctx.Session[SessionKey] = user.CompletedAccount;
                }
                bool ForceRedirect = ((ctx.Session[SessionKey] == null) || ((bool)ctx.Session[SessionKey] == false));
                string ReturnUrl = string.Empty;
                if ((filterContext.HttpContext.Request != null) && (!string.IsNullOrEmpty(filterContext.HttpContext.Request.RawUrl)))
                    ReturnUrl = filterContext.HttpContext.Request.RawUrl.ToString();
                if (ForceRedirect)
                    filterContext.Result = new RedirectToRouteResult("CompleteAccount", new System.Web.Routing.RouteValueDictionary {  {"ReturnUrl" , ReturnUrl} });
            }
            else
                base.OnAuthorization(filterContext);
        }
        else
            base.OnAuthorization(filterContext);
    }
}
}

然后注册到global.asax.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new LogOnAuthorize());
    }

对于任何需要授权但不执行检查的操作,我使用

[Authorize()]
[IgnoreCompleteProfileAttribute()]
public ActionResult LogOff()
{
    // Code Here
}

使用了这个类

using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class IgnoreCompleteProfileAttribute : Attribute { }

这些都很好地满足了我的需要,希望这能帮助到别人。

我认为您使用全局过滤器的方法是正确的。您只需在属性中实现一个检查,即如果当前用户经过身份验证并且缺少某些概要信息,则将其重定向到编辑概要页面。根据您实现重定向的方式,您还可以注入一些反馈消息,以显示在编辑配置文件页面上,解释它们被重定向的原因。