好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C# WebApi 异常处理解决方案

前言:上篇 c#进阶系列——webapi接口传参不再困惑:传参详解 介绍了webapi参数的传递,这篇来看看webapi里面异常的处理。关于异常处理,作为程序员的我们肯定不陌生,记得在介绍 aop的时候,我们讲过通过aop可以统一截获异常。那么在我们的webapi里面一般是怎么处理异常的呢,今天这一篇,博主带着大家一起来实践下webapi的异常处理。

为什么说是实践?因为在http://www.asp.net里面已经明确给出webapi的异常处理机制。光有理论还不够,今天我们还是来试一把。通过实践,我们可能发现一些更详尽的用法。

一、使用异常筛选器捕获所有异常

我们知道,一般情况下,webapi作为服务使用,每次客户端发送http请求到我们的webapi服务里面,服务端得到结果输出response到客户端。这个过程中,一旦服务端发生异常,会统一向客户端返回500的错误。

?

[httpget]

    public string getallchargingdata([fromuri]tb_charging obj)

    {

      throw new notimplementedexception( "方法不被支持" );

    }

我们来看看http请求

而有些时候,我们客户端需要得到更加精确的错误码来判断异常类型,怎么办呢?

记得在介绍aop的时候,我们介绍过mvc里面的iexceptionfilter接口,这个接口用于定义异常筛选器所需的方法,在webapi里面,也有这么一个异常筛选器,下面我们通过一个实例来看看具体如何实现。

首先在app_start里面新建一个类webapiexceptionfilterattribute.cs,继承exceptionfilterattribute,重写onexception方法

?

public class webapiexceptionfilterattribute : exceptionfilterattribute

   {

     //重写基类的异常处理方法

     public override void onexception(httpactionexecutedcontext actionexecutedcontext)

     {

       //1.异常日志记录(正式项目里面一般是用log4net记录异常日志)

       console.writeline(datetime.now.tostring( "yyyy-mm-dd hh:mm:ss" ) + "——" +

         actionexecutedcontext.exception.gettype().tostring() + ":" + actionexecutedcontext.exception.message + "——堆栈信息:" +

         actionexecutedcontext.exception.stacktrace);

 

       //2.返回调用方具体的异常信息

       if (actionexecutedcontext.exception is notimplementedexception)

       {

         actionexecutedcontext.response = new httpresponsemessage(httpstatuscode.notimplemented);

       }

       else if (actionexecutedcontext.exception is timeoutexception)

       {

         actionexecutedcontext.response = new httpresponsemessage(httpstatuscode.requesttimeout);

       }

       //.....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常,统一返回服务端错误500

       else

       {

         actionexecutedcontext.response = new httpresponsemessage(httpstatuscode.internalservererror);

       }

 

       base .onexception(actionexecutedcontext);

     }

   }

代码解析:通过判断异常的具体类型,向客户端返回不同的http状态码,示例里面写了两个,可以根据项目的实际情况加一些特定的我们想要捕获的异常,然后将对应的状态码写入http请求的response里面,对于一些我们无法判断类型的异常,统一返回服务端错误500。关于http的状态码,framework里面定义了一些常见的类型,我们大概看看:

?

#region 程序集 system.dll, v4.0.0.0

// c:\program files (x86)\reference assemblies\microsoft\framework\.netframework\v4.5\system.dll

#endregion

 

using system;

 

namespace system.net

{

   // 摘要:

   //   包含为 http 定义的状态代码的值。

   public enum httpstatuscode

   {

     // 摘要:

     //   等效于 http 状态 100。 system.net.httpstatuscode.continue 指示客户端可能继续其请求。

     continue = 100,

     //

     // 摘要:

     //   等效于 http 状态 101。 system.net.httpstatuscode.switchingprotocols 指示正在更改协议版本或协议。

     switchingprotocols = 101,

     //

     // 摘要:

     //   等效于 http 状态 200。 system.net.httpstatuscode.ok 指示请求成功,且请求的信息包含在响应中。 这是最常接收的状态代码。

     ok = 200,

     //

     // 摘要:

     //   等效于 http 状态 201。 system.net.httpstatuscode.created 指示请求导致在响应被发送前创建新资源。

     created = 201,

     //

     // 摘要:

     //   等效于 http 状态 202。 system.net.httpstatuscode.accepted 指示请求已被接受做进一步处理。

     accepted = 202,

     //

     // 摘要:

     //   等效于 http 状态 203。 system.net.httpstatuscode.nonauthoritativeinformation 指示返回的元信息来自缓存副本而不是原始服务器,因此可能不正确。

     nonauthoritativeinformation = 203,

     //

     // 摘要:

     //   等效于 http 状态 204。 system.net.httpstatuscode.nocontent 指示已成功处理请求并且响应已被设定为无内容。

     nocontent = 204,

     //

     // 摘要:

     //   等效于 http 状态 205。 system.net.httpstatuscode.resetcontent 指示客户端应重置(或重新加载)当前资源。

     resetcontent = 205,

     //

     // 摘要:

     //   等效于 http 状态 206。 system.net.httpstatuscode.partialcontent 指示响应是包括字节范围的 get

     //   请求所请求的部分响应。

     partialcontent = 206,

     //

     // 摘要:

     //   等效于 http 状态 300。 system.net.httpstatuscode.multiplechoices 指示请求的信息有多种表示形式。

     //   默认操作是将此状态视为重定向,并遵循与此响应关联的 location 标头的内容。

     multiplechoices = 300,

     //

     // 摘要:

     //   等效于 http 状态 300。 system.net.httpstatuscode.ambiguous 指示请求的信息有多种表示形式。 默认操作是将此状态视为重定向,并遵循与此响应关联的

     //   location 标头的内容。

     ambiguous = 300,

     //

     // 摘要:

     //   等效于 http 状态 301。 system.net.httpstatuscode.movedpermanently 指示请求的信息已移到 location

     //   头中指定的 uri 处。 接收到此状态时的默认操作为遵循与响应关联的 location 头。

     movedpermanently = 301,

     //

     // 摘要:

     //   等效于 http 状态 301。 system.net.httpstatuscode.moved 指示请求的信息已移到 location 头中指定的

     //   uri 处。 接收到此状态时的默认操作为遵循与响应关联的 location 头。 原始请求方法为 post 时,重定向的请求将使用 get 方法。

     moved = 301,

     //

     // 摘要:

     //   等效于 http 状态 302。 system.net.httpstatuscode.found 指示请求的信息位于 location 头中指定的

     //   uri 处。 接收到此状态时的默认操作为遵循与响应关联的 location 头。 原始请求方法为 post 时,重定向的请求将使用 get 方法。

     found = 302,

     //

     // 摘要:

     //   等效于 http 状态 302。 system.net.httpstatuscode.redirect 指示请求的信息位于 location 头中指定的

     //   uri 处。 接收到此状态时的默认操作为遵循与响应关联的 location 头。 原始请求方法为 post 时,重定向的请求将使用 get 方法。

     redirect = 302,

     //

     // 摘要:

     //   等效于 http 状态 303。 作为 post 的结果,system.net.httpstatuscode.seeother 将客户端自动重定向到

     //   location 头中指定的 uri。 用 get 生成对 location 标头所指定的资源的请求。

     seeother = 303,

     //

     // 摘要:

     //   等效于 http 状态 303。 作为 post 的结果,system.net.httpstatuscode.redirectmethod 将客户端自动重定向到

     //   location 头中指定的 uri。 用 get 生成对 location 标头所指定的资源的请求。

     redirectmethod = 303,

     //

     // 摘要:

     //   等效于 http 状态 304。 system.net.httpstatuscode.notmodified 指示客户端的缓存副本是最新的。 未传输此资源的内容。

     notmodified = 304,

     //

     // 摘要:

     //   等效于 http 状态 305。 system.net.httpstatuscode.useproxy 指示请求应使用位于 location 头中指定的

     //   uri 的代理服务器。

     useproxy = 305,

     //

     // 摘要:

     //   等效于 http 状态 306。 system.net.httpstatuscode.unused 是未完全指定的 http/1.1 规范的建议扩展。

     unused = 306,

     //

     // 摘要:

     //   等效于 http 状态 307。 system.net.httpstatuscode.redirectkeepverb 指示请求信息位于 location

     //   头中指定的 uri 处。 接收到此状态时的默认操作为遵循与响应关联的 location 头。 原始请求方法为 post 时,重定向的请求还将使用

     //   post 方法。

     redirectkeepverb = 307,

     //

     // 摘要:

     //   等效于 http 状态 307。 system.net.httpstatuscode.temporaryredirect 指示请求信息位于 location

     //   头中指定的 uri 处。 接收到此状态时的默认操作为遵循与响应关联的 location 头。 原始请求方法为 post 时,重定向的请求还将使用

     //   post 方法。

     temporaryredirect = 307,

     //

     // 摘要:

     //   等效于 http 状态 400。 system.net.httpstatuscode.badrequest 指示服务器未能识别请求。 如果没有其他适用的错误,或者不知道准确的错误或错误没有自己的错误代码,则发送

     //   system.net.httpstatuscode.badrequest。

     badrequest = 400,

     //

     // 摘要:

     //   等效于 http 状态 401。 system.net.httpstatuscode.unauthorized 指示请求的资源要求身份验证。 www-authenticate

     //   头包含如何执行身份验证的详细信息。

     unauthorized = 401,

     //

     // 摘要:

     //   等效于 http 状态 402。 保留 system.net.httpstatuscode.paymentrequired 以供将来使用。

     paymentrequired = 402,

     //

     // 摘要:

     //   等效于 http 状态 403。 system.net.httpstatuscode.forbidden 指示服务器拒绝满足请求。

     forbidden = 403,

     //

     // 摘要:

     //   等效于 http 状态 404。 system.net.httpstatuscode.notfound 指示请求的资源不在服务器上。

     notfound = 404,

     //

     // 摘要:

     //   等效于 http 状态 405。 system.net.httpstatuscode.methodnotallowed 指示请求的资源上不允许请求方法(post

     //   或 get)。

     methodnotallowed = 405,

     //

     // 摘要:

     //   等效于 http 状态 406。 system.net.httpstatuscode.notacceptable 指示客户端已用 accept 头指示将不接受资源的任何可用表示形式。

     notacceptable = 406,

     //

     // 摘要:

     //   等效于 http 状态 407。 system.net.httpstatuscode.proxyauthenticationrequired 指示请求的代理要求身份验证。

     //   proxy-authenticate 头包含如何执行身份验证的详细信息。

     proxyauthenticationrequired = 407,

     //

     // 摘要:

     //   等效于 http 状态 408。 system.net.httpstatuscode.requesttimeout 指示客户端没有在服务器期望请求的时间内发送请求。

     requesttimeout = 408,

     //

     // 摘要:

     //   等效于 http 状态 409。 system.net.httpstatuscode.conflict 指示由于服务器上的冲突而未能执行请求。

     conflict = 409,

     //

     // 摘要:

     //   等效于 http 状态 410。 system.net.httpstatuscode.gone 指示请求的资源不再可用。

     gone = 410,

     //

     // 摘要:

     //   等效于 http 状态 411。 system.net.httpstatuscode.lengthrequired 指示缺少必需的 content-length

     //   头。

     lengthrequired = 411,

     //

     // 摘要:

     //   等效于 http 状态 412。 system.net.httpstatuscode.preconditionfailed 指示为此请求设置的条件失败,且无法执行此请求。

     //   条件是用条件请求标头(如 if-match、if-none-match 或 if-unmodified-since)设置的。

     preconditionfailed = 412,

     //

     // 摘要:

     //   等效于 http 状态 413。 system.net.httpstatuscode.requestentitytoolarge 指示请求太大,服务器无法处理。

     requestentitytoolarge = 413,

     //

     // 摘要:

     //   等效于 http 状态 414。 system.net.httpstatuscode.requesturitoolong 指示 uri 太长。

     requesturitoolong = 414,

     //

     // 摘要:

     //   等效于 http 状态 415。 system.net.httpstatuscode.unsupportedmediatype 指示请求是不支持的类型。

     unsupportedmediatype = 415,

     //

     // 摘要:

     //   等效于 http 状态 416。 system.net.httpstatuscode.requestedrangenotsatisfiable 指示无法返回从资源请求的数据范围,因为范围的开头在资源的开头之前,或因为范围的结尾在资源的结尾之后。

     requestedrangenotsatisfiable = 416,

     //

     // 摘要:

     //   等效于 http 状态 417。 system.net.httpstatuscode.expectationfailed 指示服务器未能符合 expect

     //   头中给定的预期值。

     expectationfailed = 417,

     //

     upgraderequired = 426,

     //

     // 摘要:

     //   等效于 http 状态 500。 system.net.httpstatuscode.internalservererror 指示服务器上发生了一般错误。

     internalservererror = 500,

     //

     // 摘要:

     //   等效于 http 状态 501。 system.net.httpstatuscode.notimplemented 指示服务器不支持请求的函数。

     notimplemented = 501,

     //

     // 摘要:

     //   等效于 http 状态 502。 system.net.httpstatuscode.badgateway 指示中间代理服务器从另一代理或原始服务器接收到错误响应。

     badgateway = 502,

     //

     // 摘要:

     //   等效于 http 状态 503。 system.net.httpstatuscode.serviceunavailable 指示服务器暂时不可用,通常是由于过多加载或维护。

     serviceunavailable = 503,

     //

     // 摘要:

     //   等效于 http 状态 504。 system.net.httpstatuscode.gatewaytimeout 指示中间代理服务器在等待来自另一个代理或原始服务器的响应时已超时。

     gatewaytimeout = 504,

     //

     // 摘要:

     //   等效于 http 状态 505。 system.net.httpstatuscode.httpversionnotsupported 指示服务器不支持请求的

     //   http 版本。

     httpversionnotsupported = 505,

   }

}

定义好了异常处理方法,剩下的就是如何使用了。可以根据实际情况,在不同级别使用统一的异常处理机制。

1、接口级别

?

[webapiexceptionfilter]

     [httpget]

     public string getallchargingdata([fromuri]tb_charging obj)

     {

       throw new notimplementedexception( "方法不被支持" );

     }

执行到异常后,会先进到onexception方法:

执行完成之后浏览器查看:

如果需要,甚至可以向status code里面写入自定义的描述信息,并且还可以向我们的response的content里面写入我们想要的信息。我们稍微改下onexception方法:

?

if (actionexecutedcontext.exception is notimplementedexception)

       {

         var oresponse = new httpresponsemessage(httpstatuscode.notimplemented);

         oresponse.content = new stringcontent( "方法不被支持" );

         oresponse.reasonphrase = "this func is not supported" ;

         actionexecutedcontext.response = oresponse;

       }

看看reasonphrase描述信息

看看response的描述信息

2、控制器级别

如果想要某一个或者多个控制器里面的所有接口都使用异常过滤,直接在控制器上面标注特性即可。

某一个控制器上面启用异常过滤

?

[webapiexceptionfilter]

   public class chargingcontroller : baseapicontroller

   {

     #region get

     [httpget]

     public string getallchargingdata([fromuri]tb_charging obj)

     {

       throw new notimplementedexception( "方法不被支持" );

     }

   }

多个控制器上面同时启用异常过滤

?

[webapiexceptionfilter]

  public class baseapicontroller : apicontroller

  {

  }

?

public class chargingcontroller : baseapicontroller

   {

     #region get

     [httpget]

     public string getallchargingdata([fromuri]tb_charging obj)

     {

       throw new notimplementedexception( "方法不被支持" );

     }

   }

这样,所有继承baseapicontroller的子类都会启用异常过滤。

3、全局配置

如果需要对整个应用程序都启用异常过滤,则需要做如下两步:

1、在global.asax全局配置里面添加 globalconfiguration.configuration.filters.add(new webapiexceptionfilterattribute()); 这一句,如下:

?

void application_start( object sender, eventargs e)

     {

       // 在应用程序启动时运行的代码

       arearegistration.registerallareas();

       globalconfiguration.configure(webapiconfig.register);

       routeconfig.registerroutes(routetable.routes);

       globalconfiguration.configuration.filters.add( new webapiexceptionfilterattribute());

     }

2、在webapiconfig.cs文件的register方法里面添加 config.filters.add(new webapiexceptionfilterattribute()); 这一句,如下:

?

public static void register(httpconfiguration config)

     {

       //跨域配置

       config.enablecors( new enablecorsattribute( "*" , "*" , "*" ));

 

       // web api 路由

       config.maphttpattributeroutes();

 

       routetable.routes.maphttproute(

         name: "defaultapi" ,

         routetemplate: "api/{controller}/{action}/{id}" ,

         defaults: new { id = routeparameter.optional }

       ).routehandler = new sessioncontrollerroutehandler();

 

       config.filters.add( new webapiexceptionfilterattribute());

     }

二、httpresponseexception自定义异常信息

上面说的是全局的异常捕获以及处理方式,在某些情况下,我们希望以异常的方式向客户端发送相关信息,可能就需要用到我们的httpresponseexception。比如:

?

[httpget]

     public tb_charging getbyid( string id)

     {

       //从后台查询实体

       var omodel = server.find(id);

       if (omodel == null )

       {

         var resp = new httpresponsemessage(httpstatuscode.notfound)

         {

           content = new stringcontent( string .format( "没有找到id={0}的对象" , id)),

           reasonphrase = "object is not found"

         };

         throw new httpresponseexception(resp);

       }

       return omodel;

     }

执行之后浏览器里面查看结果:

代码释疑:细心的朋友可能,发现了,这里既使用了httpresponsemessage,又使用了httpresponseexception,那么,像这种可控的异常,我们是否可以直接以httpresponsemessage的形式直接返回到客户端而不用抛出异常呢?这里就要谈谈这两个对象的区别了,博主的理解是httpresonsemessage对象用来响应讯息并包含状态码及数据内容,httpresponseexception对象用来向客户端返回包含错误讯息的异常。

在网上看到一篇文章这样描述两者的区别:当呼叫 web api 服务时发生了与预期上不同的错误时,理当应该中止程序返回错误讯息,这时对于错误的返回就该使用 httpresponseexception,而使用 httpresponsemessage 则是代表着当客户端发送了一个工作请求而 web api 正确的完成了这个工作,就能够使用 httpresponsemessage 返回一个 201 的讯息,所以 httpresponsemessage 与 httpresponseexception 在使用上根本的目标就是不同的,用 httpresponsemessage 去返回一个例外错误也会让程序结构难以辨别且不够清晰。

三、返回httperror

httperror对象提供一致的方法来响应正文中返回错误的信息。准确来说,httperror并不是一个异常,只是用来包装错误信息的一个对象。其实在某一定的程度上,httperror和httpresponsemessage使用比较相似,二者都可以向客户端返回http状态码和错误讯息,并且都可以包含在httpresponseexception对象中发回到客户端。但是,一般情况下,httperror只有在向客户端返回错误讯息的时候才会使用,而httpresponsemessage对象既可以返回错误讯息,也可返回请求正确的消息。其实关于httperror没什么特别好讲的,我们来看一个例子就能明白:

?

public httpresponsemessage update(dynamic obj)

     {

       tb_product omodel = null ;

       try

       {

         var id = convert.tostring(obj.id);

         omodel = newtonsoft.json.jsonconvert.deserializeobject<tb_product>(convert.tostring(obj.datamodel));

 

         //...复杂的业务逻辑

 

 

       }

       catch (exception ex)

       {

         return request.createerrorresponse(httpstatuscode.badrequest, ex.message);

       }

 

       return request.createresponse<tb_product>(httpstatuscode.ok, omodel);

 

     }

假如现在在执行try里面复杂业务逻辑的时候发生了异常,我们捕获到了异常然后向客户端返回httperror对象,这个对象里面包含我们自定义的错误讯息,如果正常则返回httpresponsemessage对象。

如果请求异常:

如果请求正常

四、总结

以上三种异常的处理方法,可以根据不同的场景选择使用。

如果项目对异常处理要求并不高,只需要记录好异常日志即可,那么使用异常筛选器就能够搞定 如果项目需要对不同的异常,客户端做不同的处理。而这个时候使用异常筛选器不能详尽所有的异常,可能使用httpresponseexception对象是更好的选择,定义更加精细的异常和异常描述。 对于何时使用httperror,又何时使用httpresponsemessage,可以参考上文三里面用法。 当然实际项目中很可能以上两种或者三种同时使用。

上文通过一些简单的示例介绍了下webapi里面异常的处理机制,可能不够深入,但对于一般项目的异常处理基本够用。其实有一点博主还没有想明白,对于构造函数里面的异常该如何统一捕获呢?通过异常筛选器是捕获不到的,不知道园友们有没有什么更好的办法,不吝赐教,感谢感谢!如果本文能帮到你,不妨推荐下,您的推荐是博主继续总结的动力!也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/landeanfen/p/5363846.html

dy("nrwz");

查看更多关于C# WebApi 异常处理解决方案的详细内容...

  阅读:71次