MVC JQuery身份验证在单页应用程序上不起作用
我有一张签到表MVC JQuery身份验证在单页应用程序上不起作用,jquery,asp.net-mvc,forms-authentication,Jquery,Asp.net Mvc,Forms Authentication,我有一张签到表 @if (@User.Identity.IsAuthenticated) { <div>Welcome @User.Identity.Name</div> } else { <input type="text" id="username" name="username" placeholder="" class="input-xlarge"> <input type="password" id="password"
@if (@User.Identity.IsAuthenticated)
{
<div>Welcome @User.Identity.Name</div>
}
else
{
<input type="text" id="username" name="username" placeholder="" class="input-xlarge">
<input type="password" id="password" name="password" placeholder="" class="input-xlarge">
<button id="loginBtn" class="btn btn-success">Login</button>
}
和一些服务器端代码来处理请求
[HttpPost]
public ActionResult Authenticate(string username, string password)
{
var ticket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.AddDays(5),
true,
string.Empty,
FormsAuthentication.FormsCookiePath);
var encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return PartialView("_login");
}
奇怪的是,这是可行的,但不是在最初的通话中。即使用户经过身份验证,返回的视图也不会更新。如果我刷新页面,一切正常。问题是,这是一个单页应用程序,我真的不想强制刷新页面
返回的PartialView没有呈现“欢迎”文本有什么原因吗?只有后续请求经过身份验证,因为它们在请求中包含表单身份验证cookie
[HttpPost]
public ActionResult Authenticate(string username, string password)
{
var ticket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.AddDays(5),
true,
string.Empty,
FormsAuthentication.FormsCookiePath);
var encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return PartialView("_login");
}
因此,在最初的通话中,我需要小心不要使用当前主体。您是设置登录用户还是只是手动将cookie发送回客户端?我的理解是添加cookie就是“登录用户”。是否还有其他人需要在服务器端执行此操作?我认为,在服务器接收到cookie后,发送回cookie会让用户登录,但由于cookie在响应中,而不是请求中,因此对于此请求,用户身份仍不会填充。不确定是否有直接的答案,但我可以想到的两种解决方法是:1)使用模型上的属性进行“justAuthenticated”之类的操作,或2)从客户端执行额外的往返AJAX调用,然后调用Cookie,希望有人能得到“真实”的答案。出于好奇,您手动颁发身份验证票证和cookie而不是使用提供程序的具体原因是什么?的可能重复(是的,因为设置cookie的请求将不会通过身份验证,因此需要新的asp.net管道来验证用户)