好久没有写博客了 今天就来聊聊asp.net webapi的过滤器们

过滤器主要有这么几种

AuthorizationFilterAttribute 权限验证

ActionFilterAttribute 日志 参数验证等

ExceptionFilterAttribute 异常处理捕获

我是如何使用这些过滤器的,最近在做项目中,这几种过滤器我都使用了,实现当别人调用接口的时候,首先验证权限,这个验证信息可以从Head里取也可以从Body里取,然后就是验证参数的有效性,参数需要后台验证,在实体里我都是定义了验证特性,拦截器正好根据这些特性统一做后台验证,所以我的后台数据验证统一在这一步就做完了,如果不符合直接抛出给客户端,然后还可以写日志,最后是异常的捕获,异常拦截器统一捕获异常,我在其它层就不要额外的做异常处理(事务方法除外,事务需要捕获异常回滚)

这些过滤器 作为全局过滤器直接配置好 不用每个api controller都去声明特性

    /// <summary>
/// 接口的权限验证
/// Token身份验证,只有合法的用户才可以访问 否则会转向到登录页面或者无权限提示页面
/// </summary>
public class AuthGlobalAttribute : AuthorizationFilterAttribute
{
public string Roles { get; set; } public string Users { get; set; } public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
{
return;
}
string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = actionContext.ActionDescriptor.ActionName;
HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];//获取传统context
HttpRequestBase request = context.Request;//定义传统request对象
if (request["Token"] == null && actionContext.Request.Headers.Authorization == null)
{
Result result = new Result { Flag = false, Message = "缺少Token身份信息", Code="" };
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
actionContext.Response = httpResponseMessage;
return;
}
//参数带有Token
string token = request["Token"];
token = (token ?? actionContext.Request.Headers.Authorization.Parameter); //根据Token获取当前用户上下文
if (UserCache.Cache.Get(token) != null)
{
HttpContext.Current.Items["User"] = UserCache.Cache.Get(token);
//获取用户上下文后 根据Roles属性比对过滤器角色 如果没有权限向外面抛401
}
else
{
Result result = UserBLL.GetUserByToken(token);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
actionContext.Response = httpResponseMessage;
//actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("您无权限访问"));
return;
}
base.OnAuthorization(actionContext);
} }
    /// <summary>
/// 全局参数验证实体
/// </summary>
public class ValidateGlobalAttribute : ActionFilterAttribute
{
/// <summary>
/// 所有实体参数接口 全局验证
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(HttpActionContext filterContext)
{
if (!filterContext.ModelState.IsValid)
{
ValidateResults vresult = new ValidateResults();
foreach (string key in filterContext.ModelState.Keys)
{
if (filterContext.ModelState[key].Errors.Count > )
{
vresult.ErrorResults.Add(new ValidateResult
{
IsValid = false,
MemberName = key,
ErrorMessage = filterContext.ModelState[key].Errors[].ErrorMessage
});
}
}
Result<ValidateResults> result = new Result<ValidateResults> { Flag = false, Message = "数据验证失败", ResultObj = vresult,Code="" };
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
filterContext.Response = httpResponseMessage;
return;
// throw new HttpResponseException(oHttpResponseMessage);
}
base.OnActionExecuting(filterContext);
} }
    /// <summary>
/// 异常全局处理
/// </summary>
public class ExceptionGlobalAtrribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
string controllerName = filterContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = filterContext.ActionContext.ActionDescriptor.ActionName;
HttpContextBase context = (HttpContextBase)filterContext.Request.Properties["MS_HttpContext"];//获取传统context
HttpRequestBase request = context.Request;//定义传统request对象
string token = string.Empty;
if (request["Token"] != null || filterContext.Request.Headers.Authorization != null)
{
token = request["Token"];
token = (token ?? filterContext.Request.Headers.Authorization.Parameter);
}
//获取当前用户上下文
UserContext user = UserCache.Cache.Get(token);
string description = filterContext.Exception.Message.ToString();
//int autokey = DaoPack.Sys_UserLogDao.GetMax<int>(m => m.AutoKey) + 1; Sys_UserLog log = new Sys_UserLog
{
//AutoKey = autokey,
ActionName = controllerName + "/" + actionName,
Description = description,
UserID = user == null ? null : (int?)user.UserID,
UserName = user == null ? null : user.UserName,
Url = request.RawUrl,
ClientIP=SysService.GetHostAddress()
};
DaoPack.Sys_UserLogDao.Insert(log);
}
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
Result result = new Result { Flag = false, Message = "接口异常",Code="" };
httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
filterContext.Response = httpResponseMessage;
return;
//throw new HttpResponseException(oHttpResponseMessage);
// base.OnException(filterContext); }
}

webapi的几种过滤器的更多相关文章

  1. 结合jquery的前后端加密解密 适用于WebApi的SQL注入过滤器 Web.config中customErrors异常信息配置 ife2018 零基础学院 day 4 ife2018 零基础学院 day 3 ife 零基础学院 day 2 ife 零基础学院 day 1 - 我为什么想学前端

    在一个正常的项目中,登录注册的密码是密文传输到后台服务端的,也就是说,首先前端js对密码做处理,随后再传递到服务端,服务端解密再加密传出到数据库里面.Dotnet已经提供了RSA算法的加解密类库,我们 ...

  2. WebApi的一种集成测试写法(in-memory)

    WebApi的一种集成测试写法(in-memory)   大家是如何对webApi写测试的呢? 1.利用Fiddler直接做请求,观察response的内容. 2.利用Httpclient做请求,断言 ...

  3. 第四节:MVC中AOP思想的体现(四种过滤器)并结合项目案例说明过滤器的实际用法

    一. 简介 MVC中的过滤器可以说是MVC框架中的一种灵魂所在,它是MVC框架中AOP思想的具体体现,所以它以面向切面的形式无侵入式的作用于代码的业务逻辑,与业务逻辑代码分离,一经推出,广受开发者的喜 ...

  4. asp.net mvc 三种过滤器

    前几天面试遇到这个问题,发现不是很了解,学习了下,这里记录下来 经常需要将用户的操作记录到日志中,或者是验证用户是否登录了网站, 面对这样的需求,以前的操作是自定义一个统一的全局方法,然后做处理, 在 ...

  5. ASP.NET MVC中有四种过滤器类型

    在ASP.NET MVC中有四种过滤器类型

  6. Wireshark的两种过滤器与BPF过滤规则

    Wirshark使用的关键就在于过滤出想要的数据包,下面介绍怎么过滤. 抓包过滤器 Wirshark有两种过滤器,一个是抓包过滤器,一个是显示过滤器,他们之间的区别在于抓包过滤器只抓取你设置的规则,同 ...

  7. 适用于WebApi的SQL注入过滤器

    开发工具:Visual Studio 2017 C#版本:C#7.1 最有效的防止SQL注入的方式是调用数据库时使用参数化查询. 但是如果是接手一个旧的WebApi项目,不想改繁多的数据库访问层的代码 ...

  8. .Net Mvc 四种过滤器

    一.授权过滤器:AuthorizationFilters 二.动作过滤:ActionFilters 三.响应过滤:ResultFilters 四.异常过滤:ExceptionFilters ===== ...

  9. WebApi自定义全局异常过滤器及返回数据格式化

    WebApi在这里就不多说了,一种轻量级的服务,应用非常广泛.我这这里主要记录下有关 WebApi的相关知识,以便日后使用. 当WebApi应用程序出现异常时,我们都会使用到异常过滤器进行日志记录,并 ...

随机推荐

  1. LeetCode OJ:Search a 2D Matrix(二维数组查找)

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  2. css两列自适应宽度布局(左定宽,右自适应)

    1.利用BFC: <div id="root"> <div class="left">左</div> <div cla ...

  3. poj2378(dfs,树形dp)

    和poj3107,poj1655一样的方法 #include<iostream> #include<cstdio> #include<cstdlib> #inclu ...

  4. 前端之JavaScript 补充

    1. BOM window location.href = "https://www.sogo.com" location.reload() // 重新加载当前页 location ...

  5. HDU - 6178:Monkeys (贪心&树上最大匹配输&输入优化)

    There is a tree having N vertices. In the tree there are K monkeys (K <= N). A vertex can be occu ...

  6. 高级C/C++编译技术之读书笔记(五)之动态库版本控制

    最近有幸阅读了<高级C/C++编译技术>深受启发,该书深入浅出地讲解了构建过程(编译.链接)中的各种细节,从多个角度展示了程序与库文件或代码的集成方法,提出了面向代码复用和系统集成的软件架 ...

  7. PS基础教程[2]渐变工具的使用

    PS中的渐变是一个很实用的工具,很多时候都会用到,我们在网页上看到的各种各样的颜色几乎都是一种渐变色,很少有一种颜色一层不变的.那么渐变如何使用呢?本次我们来介绍一下渐变的基本使用方法. 使用方法 1 ...

  8. LeetCode Valid Parenthesis String

    原题链接在这里:https://leetcode.com/problems/valid-parenthesis-string/description/ 题目: Given a string conta ...

  9. 【java规则引擎】drools6.5.0版本api简介

    在有些术语使用的时候,我有时候会用KIE项目.KIE引擎或者Drools项目.Drools引擎,大家应该理解KIE是Drools等项目的一个统称,所以在大多数情况下KIE或者特指Drools都是差不多 ...

  10. 《Troubleshooting SQL Server》读书笔记-内存管理

    自调整的数据库引擎(Self-tuning Database Engine) 长期以来,微软都致力于自调整(Self-Tuning)的SQL Server数据库引擎,用以降低产品的总拥有成本.从SQL ...