Context.User你在new的时候没有指定为SitePrincipal类型的那么在这里做这样的转换当然不行了!
首先需要确定SitePrincipal和User是相同的类型!正确的使用方法是:
在用户通过验证以后(我想你应该使用的是ASP.NET基于角色的验证),实例化自己的SitePrincipal对象然后将此对象赋值给User这样再做这个转换就没有问题了。之所以可以赋值是因为他们是相同的类型!这也是工厂方法的中心思想!

解决方案 »

  1.   

    where did you assignContext.User = new SitePrincipal();
    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
      

  2.   

    在做转换之前最好先监视一下Context.User的类型,再看看Context.User.Identity的类型!看看是不是转换错了!你在基类里面是给哪一个赋值的?只要类型一至转换是没有问题的!