webapi过滤器的使用
授权过滤器
public class CheckAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (((ReflectedHttpActionDescriptor)actionContext.ActionDescriptor).MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), true)
|| actionContext.ActionDescriptor.ControllerDescriptor.ControllerType.IsDefined(typeof(AllowAnonymousAttribute), true))
{
return;
}
string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
string actionName = actionContext.ActionDescriptor.ActionName.ToLower();
//do something
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "error");
}
}
异常过滤器
public class CatchHandleErrorAttribute: ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var ex = actionExecutedContext.Exception;
//返回错误信息
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError,ex.ToString());
}
}
注册全局过滤器
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new Filter.CheckAuthorizeAttribute());
config.Filters.Add(new Filter.CatchHandleErrorAttribute());
}