2011-10-03 47 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

我认为你在全局过滤器的正确路径。您只需在属性中执行检查,如果当前用户已通过身份验证并且缺少某些个人资料信息,则会将其重定向到编辑个人资料页面。根据您实施重定向的方式,您还可以在编辑配置文件页面中注入某种反馈消息,以解释重定向的原因。