场景:在这里,我正在尝试处理ajax调用的会话超时,但是经过大量尝试后,我可以解决该问题。我尝试了如下。
以下是一些我接受的答案。 https://stackoverflow.com/a/5242746
AuthorizeAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeFilter : AuthorizeAttribute
{
public string[] AllowedUserTypes { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (ManageSession.UserDetail == null)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = (new RedirectController().RedirectToHome());
}
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.Result = new JsonResult
{
Data = new
{
message = "sorry, but you were logged out"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();
return;
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
控制器代码
[AuthorizeFilter(AllowedUserTypes = new string[] { "DataEntry", "Admin" })]
public class MarksEntryController : BaseController
{
public JsonResult CheckSession()
{
return Json("Check Session");
}
}
Ajax呼叫
$("#btnsaveSession").click(function () {
$.ajax(
{
url: '@Url.Action("CheckSession", "MarksEntry")',
datatype: JSON,
error: function (response) {
debugger;
alert(response);
},
success: function (response) {
debugger;
if (response == 401) {
location.reload();
}
}
});
});
请让我知道我在哪里做错。预先感谢。