1. 程式人生 > >MVC session過期時如何跳轉

MVC session過期時如何跳轉

MVC專案中時,寫一個基類來判斷session是否已過期然後跳轉到指定的錯誤頁面或者登陸介面,然後讓所有的頁面都繼承這個基類,這種方法是並不會起作用的。所以我百度了一下,進行了總結。

using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;

namespace EHR.Controllers
{

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public
class AuthenticatedFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Session["key"] == null || filterContext.HttpContext.Session["key"] == "") { GoUrl(filterContext); } } private
static void GoUrl(ActionExecutingContext filterContext) { filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(new { action = "Index", controller = "Login" })); } } }

然後在每個方法前面呼叫該方法:

 [AuthenticatedFilter]
        public ActionResult otherInAffair(string parentId, string currentId)
        {
          return View();
        }