webapi的几种过滤器
好久没有写博客了 今天就来聊聊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的几种过滤器的更多相关文章
- 结合jquery的前后端加密解密 适用于WebApi的SQL注入过滤器 Web.config中customErrors异常信息配置 ife2018 零基础学院 day 4 ife2018 零基础学院 day 3 ife 零基础学院 day 2 ife 零基础学院 day 1 - 我为什么想学前端
在一个正常的项目中,登录注册的密码是密文传输到后台服务端的,也就是说,首先前端js对密码做处理,随后再传递到服务端,服务端解密再加密传出到数据库里面.Dotnet已经提供了RSA算法的加解密类库,我们 ...
- WebApi的一种集成测试写法(in-memory)
WebApi的一种集成测试写法(in-memory) 大家是如何对webApi写测试的呢? 1.利用Fiddler直接做请求,观察response的内容. 2.利用Httpclient做请求,断言 ...
- 第四节:MVC中AOP思想的体现(四种过滤器)并结合项目案例说明过滤器的实际用法
一. 简介 MVC中的过滤器可以说是MVC框架中的一种灵魂所在,它是MVC框架中AOP思想的具体体现,所以它以面向切面的形式无侵入式的作用于代码的业务逻辑,与业务逻辑代码分离,一经推出,广受开发者的喜 ...
- asp.net mvc 三种过滤器
前几天面试遇到这个问题,发现不是很了解,学习了下,这里记录下来 经常需要将用户的操作记录到日志中,或者是验证用户是否登录了网站, 面对这样的需求,以前的操作是自定义一个统一的全局方法,然后做处理, 在 ...
- ASP.NET MVC中有四种过滤器类型
在ASP.NET MVC中有四种过滤器类型
- Wireshark的两种过滤器与BPF过滤规则
Wirshark使用的关键就在于过滤出想要的数据包,下面介绍怎么过滤. 抓包过滤器 Wirshark有两种过滤器,一个是抓包过滤器,一个是显示过滤器,他们之间的区别在于抓包过滤器只抓取你设置的规则,同 ...
- 适用于WebApi的SQL注入过滤器
开发工具:Visual Studio 2017 C#版本:C#7.1 最有效的防止SQL注入的方式是调用数据库时使用参数化查询. 但是如果是接手一个旧的WebApi项目,不想改繁多的数据库访问层的代码 ...
- .Net Mvc 四种过滤器
一.授权过滤器:AuthorizationFilters 二.动作过滤:ActionFilters 三.响应过滤:ResultFilters 四.异常过滤:ExceptionFilters ===== ...
- WebApi自定义全局异常过滤器及返回数据格式化
WebApi在这里就不多说了,一种轻量级的服务,应用非常广泛.我这这里主要记录下有关 WebApi的相关知识,以便日后使用. 当WebApi应用程序出现异常时,我们都会使用到异常过滤器进行日志记录,并 ...
随机推荐
- js 设置日期函数
前三十天: var now = new Date(); var prev = now.setDate( now.getDate() - 30 ) vm.sDate = comm.getFormatDa ...
- [置顶]
Android开发百科全书
友情提示根据目录 快速查找问题 %1$s %1$d Android string 1.整型,比如"我今年23岁了",这个23是整型的.在string.xml中可以这样写,<s ...
- OneDrive网页版打不开的解决办法
发现OneDrive文件被误删了,想去网页版找回历史文件,发现网页版无法打开,而客户端是可以正常使用的,于是猜测是域名指向的主IP被封了,于是想通过客户端的IP访问 第一步,WireShark抓包 第 ...
- Unity3d 背景、音效 播放 简单demo
仅实现功能,AudioListener在MainCamera中 using UnityEngine; using System.Collections; using System.Collection ...
- 演示使用Metasploit入侵Android
文本演示怎么使用Kali Linux入侵Android手机. Kali Linux IP地址:192.168.0.112:接收连接的端口:443. 同一局域网内android手机一部(android ...
- 剑指Offer面试题:13.合并两个排序的链表
一 题目:合并两个排序的链表 题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的.例如输入下图中的链表1和链表2,则合并之后的升序链表如链表3所示. 二 代码实现 te ...
- python库之selectors
在之前的博客中已经总结过分别在windows和linux操作系统下实现socket高并发(I/O异步)的方法,可以参考基于epoll的TP传输层实现和Windows之IOCP 下面对Python中实现 ...
- LeetCode Path Sum IV
原题链接在这里:https://leetcode.com/problems/path-sum-iv/description/ 题目: If the depth of a tree is smaller ...
- LeetCode Design Log Storage System
原题链接在这里:https://leetcode.com/problems/design-log-storage-system/description/ 题目: You are given sever ...
- 利用git bash和git gui向git远程仓库提交文件
1.首先在该文件夹下git init 2.然后在github下面创建一个新仓库去存储你的代码 3.然后利用add添加远程仓库 4.然后点击stage changed 5.最后点击长传 参考链接:htt ...