Context.User你在new的时候没有指定为SitePrincipal类型的那么在这里做这样的转换当然不行了!
首先需要确定SitePrincipal和User是相同的类型!正确的使用方法是:
在用户通过验证以后(我想你应该使用的是ASP.NET基于角色的验证),实例化自己的SitePrincipal对象然后将此对象赋值给User这样再做这个转换就没有问题了。之所以可以赋值是因为他们是相同的类型!这也是工厂方法的中心思想!
首先需要确定SitePrincipal和User是相同的类型!正确的使用方法是:
在用户通过验证以后(我想你应该使用的是ASP.NET基于角色的验证),实例化自己的SitePrincipal对象然后将此对象赋值给User这样再做这个转换就没有问题了。之所以可以赋值是因为他们是相同的类型!这也是工厂方法的中心思想!
make sure you were doing something like in global.asax (.cs):
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookie[
FormsAuthentication.FormsCookieName]; if(authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
// Create an Identity object
CustomIdentity id = SecurityManager.GetUserIdentity(authTicket.Name);
//Get user Roles
ArrayList roles = SecurityManager.GetUserRoles(txtUserName.Text);
//Create a CustomPrincipal object
CustomPrincipal newUser = new CustomPrincipal(identity, roles);
Context.User = newUser;
}
}
see
http://www.thecodeproject.com/aspnet/AspNetCustomAuth.asp