我在mvc3中使用jquery ajax调用一个void函数。在该函数中,当Session输出时,它也将到达ajax的成功函数。在发送请求之前或在ajax的成功函数中,我需要知道会话是否可用。
控制器操作:
protected override void Save(Query query, string queryTitle)
{
}发布于 2014-02-17 13:16:42
为什么不捕获服务器上的会话过期,返回HTTP 401 Unauthorized,然后在jquery中检查此响应,并弹出一个“您的会话已过期,请重新登录”页面?
在初始服务器调用中需要的代码是:
protected void Save(Query query, string queryTitle)
{
// would probably be better to refactor this bit out into its own method
string sCookieHeader = Request.Headers["Cookie"];
if (Context.Session != null
&& Context.Session.IsNewSession
&& sCookieHeader != null
&& sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
{
// session has expired
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
Response.StatusCode = 401
}
else
{
// we're authenticated, so do the save
}
}在客户端:
$.ajax(serverUrl, {
data: dataToSave,
statusCode: {
200: function(response) {
// all good, continue
401: function (response) {
// session expired!
// show login box
// make ajax call to reauthenticate
// call save method again
},
});您的重新身份验证调用将如下所示:
public ActionResult Reauthenticate(username, password)
{
if (IsValidUser(username, password))
{
// sometimes used to persist user roles
string userData = string.Join("|",GetCustomUserRoles());
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
username, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
isPersistent, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
}发布于 2014-02-17 13:21:04
为什么不试试这个呢?
public void Save()
{
if (Session.IsNewSession)
{
throw new Exception("This session was just created.");
}
//Go on with save matter...
}这应该会在AJAX函数上返回一个状态500,并会导致响应落在您定义的fail方法中。
发布于 2014-02-17 13:24:51
另一种方法是在客户机上使用setInterval(),它不断地向服务器发送一个虚拟请求,以保持会话的活动状态,至少在用户进行编辑时是这样。这可能是防止用户丢失工作的最好方法。您还可以使用它来检测连接丢失。
https://stackoverflow.com/questions/21821178
复制相似问题