身份ASP网络根元素丢失

时间:2016-01-13 11:34:21

标签: c# asp.net xml entity-framework identity

我从一位现在是前同事的同事那里接受了一个C#项目。他转向了更好的事情。因为我说我在解决他的代码并为所述项目启用Identity登录时遇到了一些麻烦。

我已经研究过并发现了许多修复方法,但这两方面都没有让我走过最后一步。

项目使用EF,因此我创建了新的连接字符串,直接指向存在表的DB,并更新了IndentityModel.cs文件以适应

Web.config

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=SERVER;Initial Catalog=DB;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;" providerName="System.Data.SqlClient"/>
  <add name="Production_MonitorEntities" connectionString="metadata=res://*/Models.ProductionModel.csdl|res://*/Models.ProductionModel.ssdl|res://*/Models.ProductionModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=SERVER;initial catalog=DB;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;multipleactiveresultsets=True;application name=EntityFramework;Connection Timeout=60&quot;"  providerName="System.Data.EntityClient" />
</connectionStrings>

这是IndentityModel.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

当我注册为新用户时,我在Register.aspx.cs

中收到以下错误
IdentityResult result = manager.Create(user, Password.Text);

类型&#39; System.Xml.XmlException&#39;的例外情况发生在mscorlib.dll中但未在用户代码中处理

其他信息:缺少根元素。

我的注册类看起来像这样

  public partial class Register : Page
    {
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
            var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
            IdentityResult result = manager.Create(user, Password.Text);
            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                //string code = manager.GenerateEmailConfirmationToken(user.Id);
                //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
    }

并且完整堆栈跟踪是

[XmlException: Root element is missing.]
   System.Xml.XmlTextReaderImpl.Throw(Exception e) +72
   System.Xml.XmlTextReaderImpl.ParseDocumentContent() +5340358
   System.Xml.XmlTextReaderImpl.Read() +163
   System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options) +44
   System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options) +64
   System.Data.Entity.Migrations.Edm.ModelCompressor.Decompress(Byte[] bytes) +86
   System.Data.Entity.Migrations.History.HistoryRepository.GetLastModel(String& migrationId, String& productVersion, String contextKey) +1016
   System.Data.Entity.Internal.InternalContext.QueryForModel(DatabaseExistenceState existenceState) +38
   System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +56
   System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +54
   System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +124
   System.Data.Entity.Internal.<>c__DisplayClassf`1.<CreateInitializationAction>b__e() +76
   System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +60
   System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +395
   System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) +11
   System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +110
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +214
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +97
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +28
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
   System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path) +18
   System.Data.Entity.Infrastructure.DbQuery`1.Include(String path) +66
   System.Data.Entity.QueryableExtensions.Include(IQueryable`1 source, String path) +130
   System.Data.Entity.QueryableExtensions.Include(IQueryable`1 source, Expression`1 path) +181
   Microsoft.AspNet.Identity.EntityFramework.UserStore`6.GetUserAggregateAsync(Expression`1 filter) +259
   Microsoft.AspNet.Identity.EntityFramework.UserStore`6.FindByNameAsync(String userName) +536
   Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync(String userName) +56
   Microsoft.AspNet.Identity.<ValidateUserName>d__4.MoveNext() +376
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.<ValidateAsync>d__0.MoveNext() +247
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +568
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.<CreateAsync>d__d.MoveNext() +483
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +281
   Microsoft.AspNet.Identity.UserManagerExtensions.Create(UserManager`2 manager, TUser user, String password) +120
   ProductionMonitor.Account.Register.CreateUser_Click(Object sender, EventArgs e) in C:\Users\newmanr\Documents\Visual Studio 2015\Projects\ProductionMonitor\Account\Register.aspx.cs:19
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9669962
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3562

然后当我尝试使用已存在于用户数据库中的用户登录时,我收到相同的xml根元素缺失

类型&#39; System.Xml.XmlException&#39;的例外情况发生在mscorlib.dll中但未在用户代码中处理

其他信息:缺少根元素。

在这一行

 var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

这是完整的登录cs文件

 public partial class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register";
            // Enable this once you have account confirmation enabled for password reset functionality
            //ForgotPasswordHyperLink.NavigateUrl = "Forgot";
            OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
            var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
            }
        }

        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var signinManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationSignInManager>();

                // This doen't count login failures towards account lockout
                // To enable password failures to trigger lockout, change to shouldLockout: true
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                switch (result)
                {
                    case SignInStatus.Success:
                        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                        break;
                    case SignInStatus.LockedOut:
                        Response.Redirect("/Account/Lockout");
                        break;
                    case SignInStatus.RequiresVerification:
                        Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}", 
                                                        Request.QueryString["ReturnUrl"],
                                                        RememberMe.Checked),
                                          true);
                        break;
                    case SignInStatus.Failure:
                    default:
                        FailureText.Text = "Invalid login attempt";
                        ErrorMessage.Visible = true;
                        break;
                }
            }
        }
    }

它为我提供了这个堆栈跟踪

[XmlException: Root element is missing.]
   System.Xml.XmlTextReaderImpl.Throw(Exception e) +72
   System.Xml.XmlTextReaderImpl.ParseDocumentContent() +5340358
   System.Xml.XmlTextReaderImpl.Read() +163
   System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options) +44
   System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options) +64
   System.Data.Entity.Migrations.Edm.ModelCompressor.Decompress(Byte[] bytes) +86
   System.Data.Entity.Migrations.History.HistoryRepository.GetLastModel(String& migrationId, String& productVersion, String contextKey) +1016
   System.Data.Entity.Internal.InternalContext.QueryForModel(DatabaseExistenceState existenceState) +38
   System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +56
   System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata, DatabaseExistenceState existenceState) +54
   System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +124
   System.Data.Entity.Internal.<>c__DisplayClassf`1.<CreateInitializationAction>b__e() +76
   System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +60
   System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +395
   System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) +11
   System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +110
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +214
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +97
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +28
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
   System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path) +18
   System.Data.Entity.Infrastructure.DbQuery`1.Include(String path) +66
   System.Data.Entity.QueryableExtensions.Include(IQueryable`1 source, String path) +130
   System.Data.Entity.QueryableExtensions.Include(IQueryable`1 source, Expression`1 path) +181
   Microsoft.AspNet.Identity.EntityFramework.UserStore`6.GetUserAggregateAsync(Expression`1 filter) +259
   Microsoft.AspNet.Identity.EntityFramework.UserStore`6.FindByNameAsync(String userName) +536
   Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync(String userName) +56
   Microsoft.AspNet.Identity.Owin.<PasswordSignInAsync>d__29.MoveNext() +101
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +160
   Microsoft.AspNet.Identity.Owin.SignInManagerExtensions.PasswordSignIn(SignInManager`2 manager, String userName, String password, Boolean isPersistent, Boolean shouldLockout) +127
   ProductionMonitor.Account.Login.LogIn(Object sender, EventArgs e) in C:\Users\newmanr\Documents\Visual Studio 2015\Projects\ProductionMonitor\Account\Login.aspx.cs:36
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9669962
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.<ProcessRequestMainAsync>d__523.MoveNext() +5911

我将在此时为此写一个简单的登录信息,但我真的很想纠正这个问题并使用身份来确保它正常工作。

谢谢, [R

0 个答案:

没有答案