属性过滤器
//添加到方法上,可以添加多个
[AttributeUsage(AttributeTargets.Method,AllowMultiple =true)]
public class TestAttribute:Attribute
{
public string Permission { get; set; }
public TestAttribute(string permission) {
this.Permission = permission;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication2.App_Start.Handler;
public class AuthorizeFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
TestAttribute[] permAtts =(TestAttribute[]) filterContext.ActionDescriptor.GetCustomAttributes(typeof(TestAttribute), false);
if (permAtts.Length <= 0)
{
return;
}
long? userId = (long?)filterContext.HttpContext.Session["sss"];
if (userId == null) {
filterContext.Result = new RedirectResult("~/Login/Index");
return;
}
}
}
最后把,属性过滤接口添加到全局变量中 GlobalFilters.Filters.Add(new AuthorizeFilter());