在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Action和Filter Filter在Asp.net MVC中它只能限制于Action,Controller。 继承于ActionFilterAttribute,且可以覆写如下几个重要方法。 2:void OnActionExecuted(ActionExecutedContext):Action执行后的操作 3:void OnResultExecuting(ResultExecutingContext):解析ActionResult前执行 4:void OnResultExecuted(ResultExecutedContext):解析ActionResult后执行 系统提供的比较常见的Filter: 示例:
[AcceptVerbs(HttpVerbs.Get )]
public ActionResult Index() { var models = inter.FindAllInfo(); return View("Index", models); }
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(GuestBookInfo model) { try { inter.Add(model); var models = inter.FindAllInfo(); TempData["TempData"] = "已经成功创建"; return RedirectToAction("Index"); } catch(Exception ex) { ModelState.AddModelError("ex",ex); return View(model); } }
[ActionName ("Edit")]
public ActionResult Edit(int id)
public class NoClientCacheAttribute : ActionFilterAttribute
{ public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext.Current.Response.CacheControl = "No-Cache"; } }
[NoClientCache]
public ActionResult Details(int id)
第一:AcceptVerbsAttribute类。它继承了ActionMethodSelectorAttribute,重要的方法是重写了基类的IsValidForRequest方法,这也是起过滤作用的地方。
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
public sealed class AcceptVerbsAttribute : ActionMethodSelectorAttribute { // Fields [CompilerGenerated] private ICollection<string> <Verbs>k__BackingField; // Methods public AcceptVerbsAttribute(HttpVerbs verbs); public AcceptVerbsAttribute(params string[] verbs); private static void AddEntryToList(HttpVerbs verbs, HttpVerbs match, List<string> verbList, string entryText); internal static string[] EnumToArray(HttpVerbs verbs); public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo); // Properties public ICollection<string> Verbs { [CompilerGenerated] get; private [CompilerGenerated] set; } }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{ if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } string httpMethod = controllerContext.HttpContext.Request.HttpMethod; return this.Verbs.Contains<string>(httpMethod, StringComparer.OrdinalIgnoreCase); }
public AcceptVerbsAttribute(HttpVerbs verbs) : this(EnumToArray(verbs))
{ }
internal static string[] EnumToArray(HttpVerbs verbs) { List<string> verbList = new List<string>(); AddEntryToList(verbs, HttpVerbs.Get, verbList, "GET"); AddEntryToList(verbs, HttpVerbs.Post, verbList, "POST"); AddEntryToList(verbs, HttpVerbs.Put, verbList, "PUT"); AddEntryToList(verbs, HttpVerbs.Delete, verbList, "DELETE"); AddEntryToList(verbs, HttpVerbs.Head, verbList, "HEAD"); return verbList.ToArray(); }
private static void AddEntryToList(HttpVerbs verbs, HttpVerbs match, List<string> verbList, string entryText)
{ if ((verbs & match) != 0) { verbList.Add(entryText); } }
总结:利用Filter的特点,我们可以写一些扩展性的内容,例如:压缩页面的Attibute,无缓存的Attibute等等。
|
请发表评论