首页 > 解决方案 > 登录请求重定向到 Account/Login?ReturnUrl

问题描述

所以基本上我的索引页面中有这个简单的表格:

using (Html.BeginForm("ChangeUserName", "Manage", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <input name="newUserName" value="@ViewBag.CurrentUser.NickName" type="text" class="enterName" placeholder="Enter name" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
    <button class="enter-button">Change Name!</button>
}

这是我的ChangeUserName行动:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangeUserName(string newUserName, int roomId)
{
    bool isLogged = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
    if(!isLogged)
    {
        System.Diagnostics.Debug.WriteLine("!isLogged");
        return RedirectToAction("Index", "Home");
    }

    if (!ApplicationUserManager.IsUserNameValid(newUserName))
    {
        ModelState.AddModelError(string.Empty, "Your nickname must be between 2 and 10 english character or letters.");
        TempData["ModelState"] = ModelState;
        return RedirectToAction("Index", "Home");
    }

    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
    user.NickName = newUserName;


    // Persist the name in the database
    var identityResult = await UserManager.UpdateAsync(user);

    // Can happen for example by duplicate username
    if(!identityResult.Succeeded)
    {
        AddErrors(identityResult);
        TempData["ModelState"] = ModelState;

        return RedirectToAction("Index", "Home");
    }

    // Updates the username in the Cookies ( re-loggin )
    await SignInManager.SignInAsync(user, true, false);

    return RedirectToAction("Index", "Room", new { id = roomId });

}

ChangeUserName操作中没有一个RedirectToAction帐户/登录,但有时会发生,主要是如果我几个小时不使用该网站,然后单击“更改名称”按钮,它会重定向到:

帐户/登录?ReturnUrl=%2FManage%2FChangeUserName

根据我在互联网上的发现,这些问题可能会有所帮助:

MVC4 Windows 身份验证重定向到帐户/登录

Asp.net MVC 5 重定向到帐户/登录

但我真的无法判断它是否符合我的问题,而且我真的不明白这些答案,我应该从 Startup.auth.cs 中删除这些代码吗?

注意:添加我的启动文件:

public partial class Startup
{
    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            },
            ExpireTimeSpan = TimeSpan.FromDays(365)
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
    }
}

标签: c#.netasp.net-mvc

解决方案


推荐阅读