1.在项目下新建一个Filters的文件夹,用于放网站所有的过滤器
2.新建一个过滤器类:CheckCustomerAttribute,继承ActionFilterAttribute,重写方法OnActionExecuting
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ProductManagement.Filters
{
public class CheckCustomerAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["CustomerID"] == null)
{
filterContext.HttpContext.Response.Redirect("/login/index");
}
}
}
}
3.在需要过滤的方法上面声明一下就可以了
[Filters.CheckCustomer]
public ActionResult Index()
{
return View();
}