MVC中的Action过滤器
Action过滤器可以用在调用动作方法之前或之后,执行一些特殊的逻辑,比如用登录验证:
Action过滤器实现IActionFilter接口,该接口有两个方法:
public interface IActionFilter { void OnActionExecuted(ActionExecutedContext filterContext); void OnActionExecuting(ActionExecutingContext filterContext); }
我们先创建一个BaseController,在这个基类中重写OnActionExecuting方法,用于让其他的控制器继承此基类。如:
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using XFK.PICCInsureTravel.Common; using XinfuMall.XinfuWeb.PublicClass; namespace XFK.PICCInsureTravel.Controllers { public abstract class BaseController : Controller { public JavaScriptSerializer js = new JavaScriptSerializer(); public LogHelper log = null; public UserSession user { get; set; } public EnterpriseAccountSession enterprise { get; set; } protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); LogHelper.WriteLog("进入BaseController"); TempData["xinfuUrl"] = System.Configuration.ConfigurationManager.AppSettings["xinfuUrl"]; if (XFK.Infrastructure.Util.SessionManager.Read(UserUtil.user_sessionStr) != null) { user = XFK.Infrastructure.Util.SessionManager.Read(UserUtil.user_sessionStr) as UserSession; object enterpriseId = XFK.Infrastructure.Util.SessionManager.Read(EnterpriseUtil.enterprise_sessionId); enterprise = new EnterpriseAccountSession(); enterprise.Id = Convert.ToInt32(enterpriseId); ViewBag.UserName = user.AccountName; ViewBag.Enterpriseid = Convert.ToInt32(enterpriseId); var limitEnterprise = String.IsNullOrEmpty(ConfigurationManager.AppSettings["limitEnterprise"]) ? "" : ConfigurationManager.AppSettings["limitEnterprise"]; if (limitEnterprise.Split(',').Contains(enterprise.Id.ToString())) { System.Web.HttpContext.Current.Response.Write("对不起,所属的企业没有订购此产品的权限!"); } } else { filterContext.Result = new RedirectResult(ConfigurationManager.AppSettings["xinfuUrl"] + "mall/Login?originUrl=" + HttpUtility.UrlEncode(Request.Url.ToString())); LogHelper.WriteLog("当前访问的路径是:" + ConfigurationManager.AppSettings["xinfuUrl"] + "mall/Login?originUrl=" + HttpUtility.UrlEncode(Request.Url.ToString())); } } } }
注意,当验证不通过时,我们给filterContext.Result赋值,用于跳转页面。这个filterContext.Result属性是一个ActionResult类型的子集---RedirectResult:
当执行到filterContext.Result时,我们给它赋值以后,便会执行跳转。
这个BaseController建好以后,下面的工作就是在其他控制器中使用了:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace XFK.PICCInsureTravel.Controllers { public class HomeController : BaseController { public ActionResult Index() { return View(); } } }
参考:http://skybirdzw.blog.163.com/blog/static/72570626201781465310313/