You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Core Problem Recap

You successfully registered users (aspnetusers table has data), but after logging in with valid credentials:

  • The LoggedInTemplate doesn't show up, and you still see AnonymousTemplate even 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:
    1. Confirm you're using a MySQL-compatible EF Identity provider (like Pomelo.EntityFrameworkCore.MySql or MySql.Data.EntityFrameworkCore depending on your ASP.NET version)
    2. Open the Package Manager Console and run Update-Database to let Entity Framework auto-generate the complete Identity schema. Manual table creation often misses critical fields or relationships.

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 machineKey before, 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.

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_Click method, add explicit identity creation if it's missing (or replace the existing sign-in call with this):
    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;
        }
    }
    
    This ensures the authentication cookie is properly written to the response.

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.cs has 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 ApplicationDbContext points to the correct database (MSSQL or MySQL) when you switch back.

5. Clear Browser Cookies & Restart the App

Old, invalid cookies from your database switch can interfere with new logins:

  1. Clear your browser's cookies (specifically look for .ASPXAUTH or cookies tied to your app's domain)
  2. Restart IIS Express or your app pool to reset the application state

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:22:40