创建一个新的类用于检测
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ProcuracyRoom.Dll; namespace ProcuracyRoom.Web.WebCode { public sealed class LoginFilterAttribute:ActionFilterAttribute { static string[] FreeModules = {"test","public", "mobile" };//整个Controller可以不登录直接使用 static string[] FreeUrl = { "/home/login", "/home/logout" };//Controller里面的Action可以使用 public override void OnActionExecuting(ActionExecutingContext filterContext) { string path = filterContext.RequestContext.HttpContext.Request.Url.LocalPath.ToLower(); string action = filterContext.ActionDescriptor.ActionName ; string controller = filterContext.Controller.GetType().Name.ToLower(); if (FreeModules.Any(t=>controller.StartsWith(t))) return; if(FreeUrl.Any(t=>path.Contains(t)))return; MyUser user = MyWebApp.currentUser; if(user==null ) { filterContext.HttpContext.Response.Redirect(MyWebApp.LoginUrl); } } } }
然后在Global.asax.cs文件中加入:(如果没有此文件 需自己创建)
GlobalFilters.Filters.Add(new LoginFilterAttribute());