好久没有写博客了 今天就来聊聊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. shell编程学习1

    1.shell是操作系统的终端命令行 (1)shell可以理解为软件系统提供给用户操作的命令行界面,可以说它是人机交互的一种方式.    (2)我们可以使用shell和操作系统.uboot等软件系统进 ...

  2. win8里DNW的裸机程序下载

    1. win8要装DNW驱动首先要禁止驱动数字签名(参考百度经验:http://jingyan.baidu.com/article/3f16e003d1f4612591c103ce.html) 2.然 ...

  3. NSSet基本使用

    int main(int argc, const char * argv[]) { @autoreleasepool { //创建一个集合对象 注:如果集合中写了两次或多次同一个对象 打印只能看到一个 ...

  4. jquery 中多条件选择器,相对选择器,层次选择器的区别

    一.Jquery常用的过滤选择器如下所示: 1.:first,选取第一个元素,比如$("div:first")选取第一个div元素 2.:last,选取最后一个元素,比如$(&qu ...

  5. Lua基础---流程控制语句

    Lua提供了if语句和if else语句作为流程控制语句,当然,符合C的特点,流程语句之间可以实现嵌套操作,当然流程控制也可以和循环体结合进行控制. 1.if语句 if(布尔表达式) then --[ ...

  6. Arcgis for Js之featurelayer实现空间查询和属性查询

    空间查询和属性查询是常用的两种对数据的检索与查询方式,在本节,将讲述Arcgis for Js下如何实现featurelayer的这两种查询方式,先贴图给大家看看: 实现界面 属性查询 空间查询 看完 ...

  7. MySQL auto_increment介绍 以及 查询和修改auto_increment的方法

    一.auto_increment使用方法 .创建table时设置auto_increment属性和初始值100 create table nonove ( id bigint unsigned not ...

  8. xml(带有命名空间的)读写操作

    xml文件: <?xml version="1.0" encoding="UTF-8"?><!-- This file contains jo ...

  9. [QT][SQLITE][QTDEMO]qt5.8_sqlite数据库_demo

    qt环境:5.8 数据库:sqlite //-------------------------------------- sqlite 日期 搜索 -------------------------- ...

  10. lwip 使用记录(1)

    原子F429的lwip实验:网络实验8 NETCONN_TCP客户端实验 代码 //tcp客户端任务函数 static void tcp_client_thread(void *arg) { OS_C ...