您好,欢迎访问一九零五行业门户网

Asp.Net WebAPI中 Filter的使用以及执行顺序(收藏)

在web api中,引入了面向切面编程(aop)的思想,在某些特定的位置可以插入特定的filter进行过程拦截处理。引入了这一机制可以更好地践行dry(don’t repeat yourself)思想,通过filter能统一地对一些通用逻辑进行处理,如:权限校验、参数加解密、参数校验等方面我们都可以利用这一特性进行统一处理,今天我们来介绍filter的开发、使用以及讨论他们的执行顺序。
一、filter的开发和调用
         在默认的webapi中,框架提供了三种filter,他们的功能和运行条件如下表所示:
filter 类型
实现的接口
描述
authorization
iauthorizationfilter
最先运行的filter,被用作请求权限校验
action
iactionfilter
在action运行的前、后运行
exception
iexceptionfilter
当异常发生的时候运行
首先,我们实现一个authorizatoinfilter可以用以简单的权限控制:
                     (actioncontext.actiondescriptor.getcustomattributes<allowanonymousattribute> verifyresult = actioncontext.request.headers.authorization!= &&  == ;               (!= httperror(
一个简单的用于用户验证的filter就开发完了,这个filter要求用户的请求中带有authorization头并且参数为123456,如果通过则放行,不通过则返回401错误,并在content中提示token不正确。下面,我们需要注册这个filter,注册filter有三种方法:
第一种:在我们希望进行权限控制的action上打上authfilterattribute这个attribute:
    public class personcontroller : apicontroller     {         [authfilter]        public createresult post(createuser user)         {            return new createresult() {id = 123};         }     }
这种方式适合单个action的权限控制。
第二种,找到相应的controller,并打上这个attribute:
    [authfilter]    public class personcontroller : apicontroller     {        public createresult post(createuser user)         {            return new createresult() {id = 123};         }     }
这种方式适合于控制整个controller,打上这个attribute以后,整个controller里所有action都获得了权限控制。
第三种,找到app_start\webapiconfig.cs,在register方法下加入filter实例:
   { id =
用这种方式适合于控制所有的api,任意controller和任意action都接受了这个权限控制。
在大多数场景中,每个api的权限验证逻辑都是一样的,在这样的前提下使用全局注册filter的方法最为简单便捷,可这样存在一个显而易见的问题:如果某几个api是不需要控制的(例如登录)怎么办?我们可以在这样的api上做这样的处理:
[allowanonymous]public createresult postlogin(loginentity entity) {      //todo:添加验证逻辑       return new createresult() {id = 123456}; }
我为这个action打上了allowanonymousattribute,验证逻辑就放过了这个api而不进行权限校验。
    在实际的开发中,我们可以设计一套类似session的机制,通过用户登录来获取token,在之后的交互http请求中加上authorization头并带上这个token,并在自定义的authfilterattribute中对token进行验证,一套标准的token验证流程就可以实现了。
    接下来我们介绍actionfilter:
actionfilterattrubute提供了两个方法进行拦截:onactionexecuting和onactionexecuted,他们都提供了同步和异步的方法。
onactionexecuting方法在action执行之前执行,onactionexecuted方法在action执行完成之后执行。
我们来看一个应用场景:使用过mvc的同学一定不陌生mvc的模型绑定和模型校验,使用起来非常方便,定义好entity之后,在需要进行校验的地方可以打上相应的attribute,在action开始时检查modelstate的isvalid属性,如果校验不通过直接返回view,前端可以解析并显示未通过校验的原因。而web api中也继承了这一方便的特性,使用起来更加方便:   
 public class customactionfilterattribute : actionfilterattribute {    public override void onactionexecuting(httpactioncontext actioncontext)     {        if (!actioncontext.modelstate.isvalid)         {             actioncontext.response = actioncontext.request.createerrorresponse(httpstatuscode.badrequest,  actioncontext.modelstate);         }     } }
这个filter就提供了模型校验的功能,如果未通过模型校验则返回400错误,并把相关的错误信息交给调用者。他的使用方法和authfilterattribute一样,可以针对action、controller、全局使用。我们可以用下面一个例子来验证:
代码如下:
public class loginentity {     [required(errormessage = 缺少用户名)]    public string username { get; set; }     [required(errormessage = 缺少密码)]    public string password { get; set; } }
[allowanonymous] [customactionfilter]public createresult postlogin(loginentity entity) {     //todo:添加验证逻辑      return new createresult() {id = 123456}; }
当然,你也可以根据自己的需要解析modelstate然后用自己的格式将错误信息通过request.createresponse()返回给用户。
onactionexecuted方法我在实际工作中使用得较少,目前仅在一次部分响应数据加密的场景下进行过使用,使用方法一样,读取已有的响应,并加密后再给出加密后的响应赋值给actioncontext.response即可。
我给大家一个demo: 
public override async task onactionexecutedasync(httpactionexecutedcontext actionexecutedcontext, cancellationtoken cancellationtoken) {        var key = 10;        var responsebody = await actionexecutedcontext.response.content.readasbytearrayasync(); //以byte数组方式读取content中的数据         for (int i = 0; i < responsebody.length; i++) { responsebody[i] = (byte)(responsebody[i] ^ key); //对每一个byte做异或运算 } actionexecutedcontext.response.content = new bytearraycontent(responsebody); //将结果赋值给response的content actionexecutedcontext.response.content.headers.contenttype = mediatypeheadervalue.parse("encrypt/bytes"); //并修改content-type}
通过这个方法我们将响应的content每个byte都做了一个异或运算,对响应内容进行了一次简单的加密,大家可以根据自己的需要进行更可靠的加密,如aes、des或者rsa…通过这个方法可以灵活地对某个action的处理后的结果进行处理,通过filter进行响应内容加密有很强的灵活性和通用性,他能获取当前action的很多信息,然后根据这些信息选择加密的方式、获取加密所需的参数等等。如果加密所使用参数对当前执行的action没有依赖,也可以采取httpmessagehandler来进行处理,在之后的教程中我会进行介绍。
最后一个filter:exceptionfilter
顾名思义,这个filter是用来进行异常处理的,当业务发生未处理的异常,我们是不希望用户接收到黄页或者其他用户无法解析的信息的,我们可以使用exceptionfilter来进行统一处理:
public class exceptionfilter : exceptionfilterattribute { public override void onexception(httpactionexecutedcontext actionexecutedcontext) { //如果截获异常为我们自定义,可以处理的异常则通过我们自己的规则处理 if (actionexecutedcontext.exception is demoexception) { //todo:记录日志 actionexecutedcontext.response = actionexecutedcontext.request.createresponse( httpstatuscode.badrequest, new {message = actionexecutedcontext.exception.message}); } else { //如果截获异常是我没无法预料的异常,则将通用的返回信息返回给用户,避免泄露过多信息,也便于用户处理 //todo:记录日志 actionexecutedcontext.response = actionexecutedcontext.request.createresponse(httpstatuscode.internalservererror, new {message = "服务器被外星人拐跑了!"}); } } }
我们定义了一个exceptoinfilter用于处理未捕获的异常,我们将异常分为两类:一类是我们可以预料的异常:如业务参数错误,越权等业务异常;还有一类是我们无法预料的异常:如数据库连接断开、内存溢出等异常。我们通过http code告知调用者以及用相对固定、友好的数据结构将异常信息告诉调用者,以便于调用者记录并处理这样的异常。
[customerexceptionfilter]public class testcontroller : apicontroller { public int get(int a, int b) { if (a < b) { throw new demoexception("a必须要比b大!"); } if (a == b) { throw new notimplementedexception(); } return a*b; } }
我们定义了一个action:在不同的情况下会抛出不同的异常,其中一个异常是我们能够预料并认为是调用者传参出错的,一个是不能够处理的,我们看一下结果:
在这样的restapi中,我们可以预先定义好异常的表现形式,让调用者可以方便地判断什么情况下是出现异常了,然后通过较为统一的异常信息返回方式让调用者方便地解析异常信息,形成统一方便的异常消息处理机制。
但是,exceptionfilter只能在成功完成了controller的初始化以后才能起到捕获、处理异常的作用,而在controller初始化完成之前(例如在controller的构造函数中出现了异常)则exceptionfilter无能为力。对此webapi引入了exceptionlogger和exceptionhandler处理机制,我们将在之后的文章中进行讲解。
二、filter的执行顺序
在使用mvc的时候,actionfilter提供了一个order属性,用户可以根据这个属性控制filter的调用顺序,而web api却不再支持该属性。web api的filter有自己的一套调用顺序规则:
所有filter根据注册位置的不同拥有三种作用域:global、controller、action:
通过httpconfiguration类实例下filters.add()方法注册的filter(一般在app_start\webapiconfig.cs文件中的register方法中设置)就属于global作用域;
通过controller上打的attribute进行注册的filter就属于controller作用域;
通过action上打的attribute进行注册的filter就属于action作用域;
他们遵循了以下规则:
1、在同一作用域下,authorizationfilter最先执行,之后执行actionfilter
2、对于authorizationfilter和actionfilter.onactionexcuting来说,如果一个请求的生命周期中有多个filter的话,执行顺序都是global->controller->action;3、对于actionfilter,onactionexecuting总是先于onactionexecuted执行;
4、对于exceptionfilter和actionfilter.onactionexcuted而言执行顺序为action->controller->global;
5、对于所有filter来说,如果阻止了请求:即对response进行了赋值,则后续的filter不再执行。
关于默认情况下的filter相关知识我们就讲这么一些,如果在文章中有任何不正确的地方或者疑问,欢迎大家为我指出。
以上就是asp.net webapi中 filter的使用以及执行顺序(收藏)的详细内容。
其它类似信息

推荐信息