好久没有写博客了 今天就来聊聊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. 关于iframe和div窗口中ajax请求200状态时执行的回调问题

    上一篇说了在ajax回调里面处理iframe窗口的刷新问题,这一篇记录一下遇到的一个分别在iframe和div窗口中ajax请求200状态时执行的回调问题. 我们先来看一下ajax请求的写法(这里使用 ...

  2. [置顶] Android App引导页这些坑你自己犯过吗?

    场景:测试机:华为荣耀6x 今天我自己掉入一个很蠢蠢的坑,一个引导页搞了20多分钟,不管我怎么测试用真机还是模拟器都无法运行,但是我写的demo完全没问题,好无语,我都怀疑我是不是搞android,我 ...

  3. HAWQ取代传统数仓实践(七)——维度表技术之维度子集

    有些需求不需要最细节的数据.例如更想要某个月的销售汇总,而不是某天的数据.再比如相对于全部的销售数据,可能对某些特定状态的数据更感兴趣等.此时事实数据需要关联到特定的维度,这些特定维度包含在从细节维度 ...

  4. RAD Studio Mobile Roadmap updated,XE5 will released on next month, Andriod will be supported.

    RAD Studio Mobile Roadmap updated   Embarcadero updated his RAD Studio Mobile Roadmap. This concern ...

  5. 【MFC】SetWindowPos函数使用详解

    摘自: http://wenku.baidu.com/link?url=hYKs20rYA13TTdMl9gJ378GNOsxH1DPZPkYZVEIcipATlVBMLzjWdpd2-29fm-tq ...

  6. freemarker 常见问题

    <#setting date_format="yyyy-MM-dd"> ..设置时间格式然后获取从后台获取值${s.createTime?date}这样就能正常显示了 ...

  7. SQl_case when

  8. [Luogu4390][BOI2007]Mokia 摩基亚

    luogu 题意 支持平面内单点加一个值以及矩阵求和. 平面大小\(W\le2*10^6\),修改操作\(\le1.6*10^5\),查询操作\(\le10^4\) sol \(CDQ\)写一发. 把 ...

  9. FIR滤波器的FPGA实现方法

    FIR滤波器的FPGA实现方法 2011-02-21 23:34:15   来源:互联网    非常重要的基本单元.近年来,由于FPGA具有高速度.高集成度和高可靠性的特点而得到快速发展.随着现代数字 ...

  10. ①HttpURLConnection通过报文提交

    在进行短信发送的接口,因厂家不同,有的厂家会采用报文的格式进行短信请求的发送与接收.本文主要介绍利用HttpURLConnection进行短信报文的请求与响应. 一般的url请求分为两种,一种是GET ...