欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ASP.Net MVC AjaxSession过期提示

程序员文章站 2022-06-11 11:37:21
...

创建过滤器

public class BasicAjaxAuthAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (IsAjaxRequestAndNonExistsSession(filterContext))
        {
            AlertMessage(filterContext);
        }
    }

    private bool IsAjaxRequestAndNonExistsSession(AuthorizationContext filterContext)
    {
        return filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.HttpContext.Session == null;
    }
    private void AlertMessage(AuthorizationContext filterContext)
    {
        ContentResult errorResult = new ContentResult();
        errorResult.Content = new AjaxResult { state = ResultType.error.ToString(), message = "长时间未操作,请重新登录。" }.ToJson();
        filterContext.Result = errorResult;
    }
}

应用在Action方法上

[BasicAjaxAuth]
public ActionResult DeleteUser(string userId)
{
    ...
}