我正在使用FormsAuthenticationService和AccountMembershipService来处理成员身份并登录。我需要一种方法来强制用户在登录站点时完成他们的个人资料,或者去一个需要[Authorize()]的区域,在能够继续在网站上之前。
我正在考虑在AuthorizationContext上使用GlobalFilter,但不确定这是否可以按要求运行。
有什么想法吗?
答案 0 :(得分: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 { }
这一切都适用于我需要的东西,希望这有助于某人。
答案 1 :(得分:0)
我认为你正在使用全局过滤器走上正确的道路。您只需在属性中执行检查,如果当前用户已通过身份验证且缺少某些配置文件信息,则会将其重定向到编辑配置文件页面。根据您实施重定向的方式,您还可以在编辑个人资料页面上注入某种反馈信息,说明他们被重定向的原因。