【问题标题】:Creating a Facade over Membership Provider在 Membership Provider 上创建外观
【发布时间】:2010-10-15 03:10:02
【问题描述】:
我在 ASP.NET MVC 中使用 Membership Provider,对于大多数数据访问,我使用 nHibernate 和存储库模式。您是否建议在 Membership Provider 上使用 Facade,以便我可以创建一个存储库并使其与我的实体模型的其余部分更加内联?我还添加了额外的功能,例如向角色添加功能和创建外观将使类变得更好。
其他人对 Membership Provider 做了什么?
【问题讨论】:
标签:
asp.net
membership-provider
facade
【解决方案1】:
我已经解决了这个确切的问题。方式如下:
web.config:
<authentication mode="Forms">
<forms name="APPAUTH"
defaultUrl="/webapp/Home.mvc"
loginUrl="/webapp/Session.mvc/Login"
protection="All"
timeout="30"
path="/"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<location path="Session">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
然后我勾搭 Application_AuthenticateRequest 类似的东西:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
//no authentication cokie present
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception)
{
// Can't do anything if we can't decrypt the ticket so treat it as not there
FormsAuthentication.SignOut(); // Remove bad ticket
}
if (authTicket == null)
{
//could not decrypt cookie
return;
}
// get the role
string[] roles = authTicket.UserData.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
// Set the security context
ISecurityService security = ContainerProvider.RequestContainer.Resolve<ISecurityService>();
Models.User user = security.GetUser(authTicket.Name);
if (user == null)
{
FormsAuthentication.SignOut();
throw new HttpException((int)System.Net.HttpStatusCode.Unauthorized, "Session expired!");
}
AppIdentity id = new AppIdentity(user, !authTicket.Expired);
AppPrincipal principal = new AppPrincipal(id, roles);
Context.User = principal;
}
ContainerProvider.RequestContainer.Resolve<ISecurityService>(); 调用是对Autofac 容器的调用,但您可以在此处执行您需要/想要执行的任何操作。
AppIdentity 和 AppPrincipal 类是自定义的,因此我可以访问我的角色,但它们并不复杂。
【解决方案2】:
您可以通过继承 MembershipProvider 基类来为站点实现自己的 MembershipProvider。然后只需覆盖通过 nHibernate 执行数据访问所需的方法。
您真正必须实现的唯一功能是 ValidateUser。其余的取决于您在站点中使用的与 MembershipProvider 相关的功能。