所以基本上我的索引页中有这个简单的表格:
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 Authentication Redirect to Account/Login
Asp.net MVC 5 redirect to Account/Login
但是我不能真正确定它是否与我的问题相匹配,老实说我不理解这些答案,我应该从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);
}
}