Asp.net MVC Session过期异常的处理

一、使用MVC中的Filter来对Session进行验证

(1)方法1:

复制代码
public class MyAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
      public void OnAuthorization(AuthorizationContext filterContext)
      {
           var loginUser = filterContext.HttpContext.Session["User"];
           //When user has not login yet
           if (loginUser == null)
           {
               var redirectUrl = ConstantProvider.LoginURL + "?RedirectPath=" + filterContext.HttpContext.Request.Url;
               filterContext.Result = new RedirectResult(redirectUrl);
               return;
           }

      }
}
复制代码

(2)方法二:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GiftWeb.Controllers
{
  
    public class BaseController : Controller
    {

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            if (filterContext.HttpContext.Session["sysuserInfo"] == null)
            {

                string currentUrl = filterContext.HttpContext.Request.RawUrl;

                currentUrl = HttpUtility.UrlEncode(currentUrl);

                filterContext.HttpContext.Response.Redirect("/Login/Index?returnUrl="+currentUrl);
            }
           
        }

    }
}
复制代码

二、对于Ajax请求的中,Session失效的处理

Ajax请求中,如果遇到session过期,使用上面的方法是不能够达到效果的。实现的思路是,如果发现是Ajax请求,就返回 特定格式的Json数据 ,客户端对于这个数据进行处理,发现有Session失效的情况,就跳转到登录页面。

首先,扩展我们的MyAuthorizeAttribute

复制代码
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class MyAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
      public void OnAuthorization(AuthorizationContext filterContext)
      {
           var loginUser = filterContext.HttpContext.Session["User"];
           //When user has not login yet
           if (loginUser == null)
           {
               var redirectUrl = ConstantProvider.LoginURL + "?RedirectPath=" + filterContext.HttpContext.Request.Url;                
               if(!filterContext.HttpContext.Request.IsAjaxRequest())
               {
                   filterContext.Result = new RedirectResult(redirectUrl);
               }
               else
               {
                  filterContext.Result = new JsonResult
                                         {
                                               Data = new
                                               {
                                                   Success = false,
                                                   Message = string.Empty,
                                                   Redirect = redirectUrl
                                         }
               };
           }
           return;
      }
}
复制代码

上面判断如果请求是来自于Ajax, 就返回一个Json Result,客户端处理的代码如下:

复制代码
 $.ajax({
            type: "POST",
            url: "@Url.ContactInfoAjax()",
            success: function (msg) {
                      if (msg.Success) {
                              …….                 
                      }
                      if (msg.Redirect) {
                         window.location = msg.Redirect;
                      }
        }
});    
复制代码

 

三、处理Session过期异常的重要性

说实话,开发人员开始项目的时候,往往关注在代码实现的功能上面,也就是程序"正常 "工作时候的状态关注的更多,而对于" 非正常 "情况下,考虑的很少。

而对于这些方面的考虑,才能让我们成为更加专业的程序员,摆脱菜鸟的处境。

posted @   大空白纸  阅读(336)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示