2011-10-03 46 views
0

我正在使用FormsAuthenticationService和AccountMembershipService來處理成員資格並登錄。我需要一種方法來強制用戶在登錄到網站時完成其配置文件,或者轉到這是一個需要[Authorize()]的區域,才能在網站上繼續。ASP.Net MVC 3首次登錄/完成配置文件

我在考慮在AuthorizationContext上使用GlobalFilter,但不確定這是否會按需要工作。

任何想法?

回答

1

經過一番探索,我設法找到了實現這個目標的方法。

首先創建一個全局過濾

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 { } 

這一切都適合我需要的東西,希望這可以幫助某人。

0

我認爲你在全局過濾器的正確路徑。您只需在屬性中執行檢查,如果當前用戶已通過身份驗證並且缺少某些個人資料信息,則會將其重定向到編輯個人資料頁面。根據您實施重定向的方式,您還可以在編輯配置文件頁面中注入某種反饋消息,以解釋重定向的原因。