【发布时间】:2014-05-28 18:26:46
【问题描述】:
我正在尝试在 ASP.NET MVC 5 应用程序中实现自定义表单身份验证,但我以前没有这样做过,需要一些帮助。我没有使用会员提供程序,但已关注(部分)http://tech.pro/tutorial/1216/implementing-custom-authentication-for-aspnet。所以我使用的是 CustIdentity 和 CustPrincipal。
这是来自 Global.asax.cs 的 Application_AuthenticateRequest:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new CustIdentity(ticket);
var principal = new CustPrincipal(identity);
HttpContext.Current.User = principal;
}
}
目前运行良好,我可以在上述方法结束时成功调用 HttpContext.Current.User.IsInRole("Admin")。
但是,当我从视图中尝试 User.IsInRole("Admin") 时,我得到:'在调用“WebSecurity”类的任何其他方法之前,您必须调用“WebSecurity.InitializeDatabaseConnection”方法'因为我这样做了不使用成员资格提供程序,WebSecurity.InitializeDatabaseConnection 不应该应用(我已经有我的 SQL 用户表等设置)。
所以我试试
var user = User as CustPrincipal;
if (user != null && user.IsInRole("Admin"))
....
但不能将 User 强制转换为 CustPrincipal,因此始终返回 null。
我在这里缺少什么?
【问题讨论】:
标签: asp.net-mvc forms-authentication asp.net-mvc-5