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");
}