在MVC中添加拦截器实现登录后的权限验证
1.新建一个类 (以下实现了打印日志功能)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcReporistory.Controllers { public class LoggerFilter : FilterAttribute, IActionFilter { void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { System.Web.HttpContext.Current.Response.Write("执行action前拦截"); filterContext.Controller.ViewData["ExecutingLogger"] = "正要添加公告,已以写入日志!时间:" + DateTime.Now; } void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) { System.Web.HttpContext.Current.Response.Write("执行action后拦截"); filterContext.Controller.ViewData["ExecutedLogger"] = "公告添加完成,已以写入日志!时间:" + DateTime.Now; } } }
2.在控制器中用[LoggerFilter] 标识这个控制器类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcReporistory.Controllers { [LoggerFilter] public class BookController : Controller,IActionFilter { // // GET: /Book/ private Domain.IBookRepository.IBookRepository bookRepository; private Domain.Infrastructure.IUnitOfWork unitOfWork; public BookController() { Domain.Infrastructure.BookStoreDbContext bookStoreDbContext = new Domain.Infrastructure.BookStoreDbContext(); bookRepository = new DAL.Repository.BookRepository(bookStoreDbContext); unitOfWork = new Domain.Infrastructure.UnitOfWork(bookStoreDbContext); } public ActionResult List() { IList<Domain.Models.Book> listBook = bookRepository.GetAllBooks(); ViewBag.listdata = listBook; return View(listBook); } public ActionResult Cre() { Random rn=new Random(); Domain.Models.Book book = new Domain.Models.Book(); book.ISBN = rn.Next(1000,1000000).ToString(); book.Title = "aaaa"; book.Type = "类型"; Create(book); return View(); } public ActionResult Create(Domain.Models.Book book) { bookRepository.Insert(book); unitOfWork.Save(); return RedirectToAction("List"); } } }