好久没有写博客了 今天就来聊聊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. form表单的提交地址一定要是完整的绝对地址

    <form action="<%=path%>/servlet/DologinServlet" =<form action="<%=requ ...

  2. 【设计模式】calendar的单例需求和实现

    calendar单例需求: 参数:有default的calendar file 1.如果无实例,无参数调用,取default,检查是否合法,存入实例 2.如果无实例,有参数调用,检查是否合法,存入实例 ...

  3. 关于socket绑定INADDR_ANY

    其中INADDR_ANY就是指定地址为0.0.0.0的地址,这个地址事实上表示不确定地址,或“所有地址”.“任意地址”. 一般情况下,如果你要建立网络服务器,则你要通知服务器操作系统:请在某地址 xx ...

  4. H264的nalu type有哪些?

    1.forbidden_bit:                             禁止位,初始为0,当网络发现NAL单元有比特错误时可设置该比特为1,以便接收方纠错或丢掉该单元. 2.nal_ ...

  5. make: *** No rule to make target `out/target/common/obj/APPS/framework-res_intermediates/src/R.stamp'

    /********************************************************************************** * make: *** No r ...

  6. (十一)java循环结构

    while(循环的条件) {循环的语句} int a = 1; while(a < 5) { System.out.println(a);//1,2,3,4 a++; } System.out. ...

  7. 深入理解java虚拟机-第七章

    第7章 虚拟机类加载机制 类的加载的时机 加载 Loading, 连接 Linking(验证 Verfiication, 准备Preparation, 解析 Resolution) 初始化 Initi ...

  8. c printf打印格式

    关于小数点位数的举例:  <pre lang="c" escaped="true">#include <stdio.h> /* 当fah ...

  9. Python之numpy库

    NumPy库知识结构 更多详细内容参考:http://www.cnblogs.com/zhanglin-0/p/8504635.html

  10. 模糊聚类算法(FCM)

    伴随着模糊集理论的形成.发展和深化,RusPini率先提出模糊划分的概念.以此为起点和基础,模糊聚类理论和方法迅速蓬勃发展起来.针对不同的应用,人们提出了很多模糊聚类算法,比较典型的有基于相似性关系和 ...