webapi Filter

时间:2021-02-14 05:36:53

webapi的controller和action的控制。

使用场景:webapi接收到加密数据以及签名。验证签名是否有效。我们不能一个个action增加判断。

所以添加Filter是比较明智的方法。

首先 签名过滤器

namespace API.Filters
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class APISignAttribute : ActionFilterAttribute
{
public static readonly string APISign = WebConfigurationManager.AppSettings["APISign"]; public override void OnActionExecuting(HttpActionContext actionContext)
{ if (IsVaild(actionContext))
{
base.OnActionExecuting(actionContext);
}
else
{
throw new Exception("Invalid sign");
} } public bool IsVaild(HttpActionContext actionContext)
{
var sign = HttpContext.Current.Request.Form["data"].ToString();
//开始判断逻辑 return false;
} public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// 若发生例外则不在这边处理
if (actionExecutedContext.Exception != null)
return; base.OnActionExecuted(actionExecutedContext);
}
}
}

异常过滤器

public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
base.OnException(actionExecutedContext); var result = new apiResult<object>()
{
code = HttpStatusCode.BadRequest,
msg = actionExecutedContext.Exception.Message
};
if (actionExecutedContext.Exception is InvalidTokenException)
{
result.code = HttpStatusCode.Unauthorized;
}
string msg = "\r\n" + "apiErrorHandelattribute.StackTrace:\r\n" + actionExecutedContext.Exception.StackTrace + "\r\n\r\n" + "Message:\r\n" + actionExecutedContext.Exception.Message + "\r\n\r\n";
LogerHelper.WriteLog(msg); // 重新打包回传的讯息
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(result.code, result); }

然后是启用方式,有2种

1 全局控制 在webapiConfig中添加

config.Filters.Add(new APISignAttribute());
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
); //注册 sign统一验证
config.Filters.Add(new APISignAttribute()); //注册 api异常处理
//config.Filters.Add(new ApiErrorHandleAttribute());
}
}

2 局部的控制

加在action上代表需要进入filter

加在controller上,代表该controller中所有action都要进入filter

[APISignAttribute]
public class TestController : BaseControllerAPI
{
[HttpPost]
public dynamic Get()
{
apiResult<dynamic> result = new apiResult<dynamic>();
result.data= new List<string>() { "", "" }; return result; } [APISignAttribute]
[HttpGet]
public dynamic haha()
{
return "value1";
}
}

结束webapi Filter