一、权限认证过滤器:
public class AuthFilterAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//如果用户方位的Action带有AllowAnonymousAttribute,则不进行授权验证
if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
{
return;
}
var dicHeader = actionContext.Request.Headers.ToDictionary(r => r.Key, r => r.Value);
//var verifyResult = actionContext.Request.Headers.Authorization != null && actionContext.Request.Headers.Authorization.Scheme == "123456";
var verifyResult = dicHeader.Any(r => r.Key == "Authorization" && r.Value != null && r.Value.Contains("123456"));
if (!verifyResult)
{
//如果验证不通过,则返回401错误,并且Body中写入错误原因
//actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("Token 不正确"));
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "请登录");
}
}
}
二、在请求前后执行:
public class MyActionAttribute : ActionFilterAttribute
{
/// <summary>
/// 在Action方法运行之前调用
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
//2.获取控制器作用的Controller和action的名字
string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = actionContext.ActionDescriptor.ActionName;
//HttpContext.Current.Response.Write("行为过滤器OnActionExecuting作用于" + controllerName + "控制器下的" + actionName + "方法运行之前");
//1.如果保留如下代码,则会运行.net framework定义好的行为验证,如果希望自定义行为验证,则删除如下代码
base.OnActionExecuting(actionContext);
}
/// <summary>
/// 在Action方法运行之后调用
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
//2.获取控制器作用的Controller和action的名字
string controllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName.ToLower();
string actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName.ToLower();
//HttpContext.Current.Response.Write("行为过滤器OnActionExecuted作用于" + controllerName + "控制器下的" + actionName + "方法运行之后");
//1.如果保留如下代码,则会运行.net framework定义好的行为验证,如果希望自定义行为验证,则删除如下代码
base.OnActionExecuted(actionExecutedContext);
}
}
三、异常处理过滤器:
public class MyExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception is LingbugException)
{
//如果截获异常为我们自定义,可以处理的异常则通过我们自己的规则处理
//自定义异常,如校验不通过等手动抛出的异常
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, new { Message = actionExecutedContext.Exception.Message });
}
else
{
//如果截获异常是我没无法预料的异常,则将通用的返回信息返回给用户,避免泄露过多信息,也便于用户处理
//系统异常
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new { Message = "服务器被外星人拐跑了!" });
}
}
}
Ending......