1、ActionFilterAttribute 使用示例
namespace Demo.Filter { public class ActionTestFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.ViewBag.TestString = "过滤测试";//全局变量 filterContext.Controller.ViewBag.domainName = filterContext.HttpContext.Request.Url.Authority;//获取域名 filterContext.Controller.ViewBag.module = filterContext.HttpContext.Request.Url.Segments[1].Replace(‘/‘, ‘ ‘).Trim();//获取模块名称 filterContext.Controller.ViewBag.controllerName = filterContext.RouteData.Values["controller"].ToString();//获取 controllerName 名称 filterContext.Controller.ViewBag.actionName = filterContext.RouteData.Values["action"].ToString();//获取ACTION 名称 //filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { Controller = "Home", action = "RedirectHtml" }));//页面重定向 //filterContext.Result = new RedirectResult("http://www.baidu.com"); //filterContext.Result = new HttpUnauthorizedResult(); //filterContext.Result = new ContentResult { Content = @"返回文本" }; base.OnActionExecuting(filterContext); } } }
以特性的形式放在controller 或者action 前面
[ActionTestFilter] public ActionResult Index() { return View(); } 页面使用变量@viewbag.变量名
时间: 2024-11-05 06:32:27