webAPI 有几个常用的筛选器, 都是虚函数类型, 只要重写了, 就可以在方法, 类, 派生类使用, 属于 System.NET.Http.Filter.
ActionFilterAttribute:Action 操作筛选器, 一般重写执行前, 执行后的 2 个方法;
AuthorizationFilterAttribute: 授权筛选器, 有请求授权时的方法;
ExceptionFilterAttribute: 异常筛选器, 有引起异常的方法;
ActionFilterAttribute 重写:
- /// <summary>
- /// 执行操作前的过滤器 (可以在方法, 类, 派生类使用)
- /// </summary>
- [AttributeUsageAttribute(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
- public class MyActionFilter : ActionFilterAttribute
- {
- /// <summary>
- /// 操作筛选器之前
- /// </summary>
- /// <param name="actionContext"></param>
- public override void OnActionExecuting(HttpActionContext actionContext)
- {
- bool Login = true;
- var token = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query).GetValues("token")[0].ToString();
- if (!string.IsNullOrEmpty(token))
- {
- // 获取到 token, 再判断是否存在
- if (!ChkToken(token.ToString())) { Login = false; }
- }
- else
- {
- Login = false;
- }
- if(!Login)
- {
- // 请求返回结果
- string jsonString = "{\"msg\":\" 未登录 \",\"code\":\"-1\"}";
- HttpResponseMessage reqMsg = new HttpResponseMessage { Content=new StringContent(jsonString,System.Text.Encoding.GetEncoding("UTF-8"), "application/json") };
- actionContext.Response = reqMsg;
- }
- base.OnActionExecuting(actionContext);
- }
- }
来源: http://www.bubuko.com/infodetail-3433920.html