Contact Manager Web API 示例[4] 异常处理(Exception Handling)

简介:

联系人管理器web API是一个Asp.net web api示例程序,演示了通过ASP.NET Web API 公开联系信息,并允许您添加和删除联系人,示例地址http://code.msdn.microsoft.com/Contact-Manager-Web-API-0e8e373d

Contact Manager Web API 示例[1]CRUD 操作 已经做了一个基本的介绍,

Contact Manager Web API 示例[2] Web API Routing 介绍Web API Routing。

Contact Manager Web API 示例[3] 分页和查询(Paging and Querying)主要介绍OData的查询和分页支持。

本文主要介绍WebAPI的异常处理HttpResponseMessage。

如果 Web API 的 controller 掷出一个异常(exception),会发生什么事?默认下,最常是会把例外转译为一个 HTTP 状态代码 500 (Internal Server Error) 回应。

HttpResponseException 类 是一个特别情况。能够构建回应的信息, 这个例外能回传任何 HTTP 状态代码。例如,下面例子,如果 id 参数不存在,会回传 404 (Not Found) 状态代码。

public HttpResponseMessage<Contact> Get(int id) 
        { 
            var contact = this.repository.Get(id); 
            if (contact == null) 
            { 
                var response = new HttpResponseMessage(); 
                response.StatusCode = HttpStatusCode.NotFound; 
                response.Content = new StringContent("Contact not found"); 
                throw new HttpResponseException(response); 
            } 
            var contactResponse = new HttpResponseMessage<Contact>(contact);

            //set it to expire in 5 minutes 
            contactResponse.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(30)); 
            return contactResponse; 
        }

异常过滤 (EXCEPTION FILTERS)

你可以通过编写 异常过滤(Exception Filter)来自己处理 Web API 的异常。当一个 controller 方法抛出任何未处理的例外,它并不是 HttpResponseException 异常,异常过滤被会执行。HttpResponseException 型别是一种特别情况,因为它是特别设计来回传 HTTP 响应。

异常过滤实现 System.Web.Http.Filters.IExceptionFilter 接口。不管如何,只需要继承 System.Web.Http.Filters.ExceptionFilterAttribute 类然后重写(override) OnException 方法。

namespace ContactManager.Filters 
{ 
    public class LogExceptionFilter : ExceptionFilterAttribute 
    { 
        public override void OnException(HttpActionExecutedContext actionExecutedContext) 
        { 
            //增加二行 Trace 代码

            Trace.TraceError("异常: {0}", actionExecutedContext.Exception.Message); 
            Trace.TraceError("请求 URI: {0}", actionExecutedContext.Request.RequestUri);

            base.OnException(actionExecutedContext); 
        } 
    } 
}

你也能自行控制 HTTP 响应让 Client 接收。在 HttpActionExecutedContext 参数 去修改或设置 Result 属性。我们新增一个 NotImplExceptionFilter 类别,一样继承 ExceptionFilterAttribute 类和重写 OnException 方法。

namespace ContactManager.Filters 
{ 
    public class NotImplExceptionFilter : ExceptionFilterAttribute 
    { 
        public override void OnException(HttpActionExecutedContext actionExecutedContext) 
        { 
            //增加二行 Trace 代码

            Trace.TraceError("异常: {0}", actionExecutedContext.Exception.Message); 
            Trace.TraceError("请求 URI: {0}", actionExecutedContext.Request.RequestUri);

            if(actionExecutedContext.Result==null) 
            { 
                actionExecutedContext.Result = new  HttpResponseMessage();

            } 
            //HttpStatusCode.NotImplemented = 501  
            actionExecutedContext.Result.StatusCode = HttpStatusCode.NotImplemented ; 
            actionExecutedContext.Result.Content = new StringContent("方法未执行");

            base.OnException(actionExecutedContext); 
        } 
    } 
}

注册异常过滤

有二种方法可以去注册异常过滤。

第一,你可以注册到全局的 GlobalConfiguration.Configuration.Filters 集合。当发生未处理的异常,异常过滤集合中会作用在所有 Web API controller action。(异常类型 HttpResponseException 也会被执行)。我们必须在 Global.asax 文件的 Application_Start 注册它。

public static void RegisterApis(HttpConfiguration config) 
{ 
   ……

    config.Filters.Add(new LogExceptionFilter());

}

 

protected void Application_Start() 
{ 
         RegisterApis(GlobalConfiguration.Configuration); 
}

第二,你可以注册异常过滤至指定的 action 方法,通过指定属性的方式。例如以下范例:

        [HttpGet] 
        [NotImplExceptionFilter] 
        public HttpResponseMessage<Contact> Get(int id) 
        { 
            var contact = this.repository.Get(id); 
            if (contact == null) 
            { 
                //var response = new HttpResponseMessage(); 
                //response.StatusCode = HttpStatusCode.NotFound; 
                //response.Content = new StringContent("Contact not found"); 
                //throw new HttpResponseException(response); 
                throw new NotImplementedException("此方法未执行"); 
            } 
            var contactResponse = new HttpResponseMessage<Contact>(contact);

            //set it to expire in 5 minutes 
            contactResponse.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(30)); 
            return contactResponse; 
        }

异常过滤在 ASP.NET Web API 与 ASP.NET MVC 类似。不管如何,他们分布在不同命名空间里。特别说明,HandleErrorAttribute 类 使用在 ASP.NET MVC,无法拿来处理 Web API controller 的异常。

本文来自云栖社区合作伙伴“doNET跨平台”,了解相关信息可以关注“opendotnet”微信公众号

目录
相关文章
|
8月前
|
Java API
使用Java访问API的示例
下面是一个使用Java访问API的示例代码:
|
8月前
|
网络安全
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://xxxx.svc.cluster.local:8080/xxxx": Connection reset; nested exception is java.net.SocketException: Connection reset 什么原因导致得
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "xxxx.svc.cluster.local:8080/xxxx ": Connection reset; nested exception is java.net.SocketException: Connection reset 什么原因导致得
950 0
|
5天前
|
存储 程序员 API
python web开发示例详解
python web开发示例详解
14 0
|
1月前
|
JSON 监控 API
在API接口对接中关键示例问题(1)
在API接口对接中,有几个关键的问题需要注意,以确保接口的稳定性、安全性和易用性。以下是这些问题及部分示例代码的简要概述
|
2月前
|
Java API PHP
获取1688商品详情API:步骤与代码示例
在电子商务领域,阿里巴巴的1688平台是一个广受商家和开发者欢迎的批发交易市场。若您是一名开发者,希望建立自己的应用程序或网站来获取并展示1688上的商品信息,您可能需要使用到1688提供的API接口。以下是获取1688商品详情API的详细步骤说明。
|
2月前
|
Java API
Java 日期和时间 API:实用技巧与示例 - 轻松处理日期和时间
简介 Scanner 类用于获取用户输入,它位于 java.util 包中。 使用 Scanner 类 要使用 Scanner 类,请执行以下步骤: 导入 java.util.Scanner 包。 创建一个 Scanner 对象,并将其初始化为 System.in。 使用 Scanner 对象的方法读取用户输入。
56 1
|
7月前
|
Java 应用服务中间件 Maven
Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerExcepti
Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerExcepti
174 0
|
3月前
|
JSON 监控 Java
Java Web开发中的异常处理与日志记录最佳实践
Java Web开发中的异常处理与日志记录最佳实践
|
3月前
|
Java
org.springframework.web.util.NestedServletException: Request processing failed; nested exception....
org.springframework.web.util.NestedServletException: Request processing failed; nested exception....
34 0
|
3月前
|
SQL 开发框架 .NET
ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能
ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能
37 0