using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace Rhythmk.Sercurity.Attribute { [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)] public class MeAttribute : FilterAttribute, IAuthorizationFilter, IActionFilter { //IAuthorizationFilter public void OnAuthorization(AuthorizationContext filterContext) { filterContext.RequestContext.HttpContext.Response.Write("OnAuthorization<br/>"); } //IActionFilter public void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.RequestContext.HttpContext.Response.Write("OnActionExecuted<br/>"); } //IActionFilter public void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.ViewBag.CurrentData = "http://Rhythmk.cnblogs.com"; if (filterContext.ActionParameters.ContainsKey("user")) { filterContext.ActionParameters["user"] = "UserID=rhythmk"; } filterContext.RequestContext.HttpContext.Response.Write("OnActionExecuting<br/>"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using Rhythmk.Sercurity.Attribute; namespace MvcApp2.Controllers { public class HomeController : Controller { [Me] // http://rhythmk.cnblogs.com public ActionResult Index(string user) { HttpContext.Response.Write(string.Format("ViewBag.CurrentData:{0}<br/>", ViewBag.CurrentData)); HttpContext.Response.Write("Home/Index<br/>"); HttpContext.Response.Write(string.Format("user:{0}<br/>",user)); return View(); } } }
输出结果:
OnAuthorization
OnActionExecuting
ViewBag.CurrentData:http://Rhythmk.cnblogs.com
Home/Index
user:UserID=rhythmk
OnActionExecuted
异常拦截:
public class ActionErrorAttribute : ActionFilterAttribute, IExceptionFilter
{
/// <summary>
/// 过滤异常信息
/// </summary>
/// <param name="filterContext"></param>
public void OnException(ExceptionContext filterContext)
{
Exception error = filterContext.Exception;
filterContext.ExceptionHandled = true; //设置异常已经处理
filterContext.RequestContext.HttpContext.Response.Write(error.Message);
}
}
使用:
[ActionError]
public ActionResult TestError()
{
int i = int.Parse("rhythmk");
return Content("OK");
}
通过拦截器 传入参数写操作日志:
public void OnActionExecuted(ActionExecutedContext filterContext)
{
string routeId = string.Empty;
if (filterContext.Controller.ViewData["CompanyId"] != null)
{
routeId = filterContext.Controller.ViewData["CompanyId"].ToString();
}
filterContext.RequestContext.HttpContext.Response.Write("OnActionExecuted<br/>"+routeId);
}