ASP.NET登录后LoggedInTemplate不显示,AnonymousTemplate仍显示求助
Hey Nick, let's break down this issue step by step—since you're new to ASP.NET, I'll keep things clear and actionable based on your description:
You successfully registered users (aspnetusers table has data), but after logging in with valid credentials:
- The
LoggedInTemplatedoesn't show up, and you still seeAnonymousTemplateeven after redirecting to Default - Invalid credentials throw errors (so the database connection/validation works), but valid logins don't persist the authenticated state
- Even switching back to MSSQL now causes the same issue, which means it's likely not a database driver problem but a configuration or schema issue introduced during the switch
1. Check if All Required Identity Tables Exist in Your Database
ASP.NET Identity relies on a full set of tables (not just aspnetusers) to persist authentication state, roles, claims, etc. Missing these will break session persistence:
- Verify your MySQL database has these tables:
aspnetroles,aspnetuserroles,aspnetuserclaims,aspnetuserlogins,aspnetusertokens
- If any are missing:
- Confirm you're using a MySQL-compatible EF Identity provider (like
Pomelo.EntityFrameworkCore.MySqlorMySql.Data.EntityFrameworkCoredepending on your ASP.NET version) - Open the Package Manager Console and run
Update-Databaseto let Entity Framework auto-generate the complete Identity schema. Manual table creation often misses critical fields or relationships.
- Confirm you're using a MySQL-compatible EF Identity provider (like
2. Validate Web.config Authentication & Cookie Settings
Login state is stored in cookies—incorrect config here will cause the system to fail recognizing authenticated users:
- Check your Web.config for these key sections:
<system.web> <!-- Ensure Forms auth is enabled with correct settings --> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" name=".ASPXAUTH" /> </authentication> <!-- Critical: If you modified this during the MySQL switch, or never set it, cookies can't be decrypted --> <machineKey validationKey="YOUR_FIXED_VALIDATION_KEY" decryptionKey="YOUR_FIXED_DECRYPTION_KEY" validation="SHA1" decryption="AES" /> </system.web>- If you didn't have a manual
machineKeybefore, add one (you can generate a key online easily). Auto-generated keys reset on app restarts, breaking existing cookies. - Double-check the
<authorization>section isn't accidentally denying authenticated users.
- If you didn't have a manual
3. Verify Login Logic Explicitly Creates an Authentication Ticket
You mentioned Login.aspx.cs is unchanged, but let's confirm the sign-in logic properly persists the user identity:
- In your
LoginButton_Clickmethod, add explicit identity creation if it's missing (or replace the existing sign-in call with this):
This ensures the authentication cookie is properly written to the response.protected void LoginButton_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>(); var user = manager.FindByName(UserName.Text); if (user != null && manager.CheckPassword(user, Password.Text)) { // Explicitly create and sign in the user identity var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); Context.GetOwinContext().Authentication.SignIn( new AuthenticationProperties { IsPersistent = RememberMe.Checked }, identity ); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid login attempt"; ErrorMessage.Visible = true; } }
4. Check Owin Startup Configuration (If Applicable)
Most ASP.NET Identity projects use Owin for auth setup—make sure this is configured correctly:
- Confirm your
Startup.cshas this block (adjust for your DbContext):public void ConfigureAuth(IAppBuilder app) { // Hook up your database context app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable cookie authentication app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); }- Ensure the connection string in
ApplicationDbContextpoints to the correct database (MSSQL or MySQL) when you switch back.
- Ensure the connection string in
5. Clear Browser Cookies & Restart the App
Old, invalid cookies from your database switch can interfere with new logins:
- Clear your browser's cookies (specifically look for
.ASPXAUTHor cookies tied to your app's domain) - Restart IIS Express or your app pool to reset the application state
内容的提问来源于stack exchange,提问作者Nick

