【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理

时间:2022-01-17 06:20:20

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本系列教程,请先看前面的内容。

Exception Handling in ASP.NET Web API
ASP.NET Web API中的异常处理

本文引自:

By Mike Wasson | March 12, 2012
作者:Mike Wasson | 日期:2012-3-12

This article describes error and exception handling in ASP.NET Web API.
本文描述ASP.NET Web API中的错误与异常处理:

HttpResponseException

Exception Filters
异常过滤器

Registering Exception Filters
注册异常过滤器

HttpError

HttpResponseException

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.
如果一个Web API控制器抛出一个未捕捉异常,会发生什么?默认地,大多数异常都会被转化成一个带有状态码“500 – 内部服务器错误”的HTTP响应。

The HttpResponseException type is a special case. This exception returns any HTTP status code that you specify in the exception constructor. For example, the following method returns 404, Not Found, if the id parameter is not valid.
HttpResponseException(HTTP响应异常)类型是一种特殊的情况。这种异常会返回你在异常构造器中指定的任何HTTP状态码。例如,在以下方法中,如果id参数非法,会返回“404 — 未找到”。

public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return item; }

For more control over the response, you can also construct the entire response message and include it with the HttpResponseException:
为了对响应进行更多控制,你也可以构造整个响应消息,并用HttpResponseException来包含它:

public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(string.Format("No product with ID = {0}", id)), ReasonPhrase = "Product ID Not Found" } throw new HttpResponseException(resp); } return item; }

Exception Filters
异常过滤器

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.
通过编写一个异常过滤器(exception filter),你可以定制Web API如何处理异常。当一个控制器抛出一个非HttpResponseException异常的未处理异常时,会执行一个异常过滤器。HttpResponseException类型一个特殊的情况,因为它是专门设计用来返回一个HTTP响应的。

Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface. The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.
异常过滤器实现System.Web.Http.Filters.IExceptionFilter接口。编写异常过滤器最简单的方式是通过System.Web.Http.Filters.ExceptionFilterAttribute类进行派生,并重写其OnException方法。

Exception filters in ASP.NET Web API are similar to those in ASP.NET MVC. However, they are declared in a separate namespace and function separately. In particular, the HandleErrorAttribute class used in MVC does not handle exceptions thrown by Web API controllers.
ASP.NET Web API中的异常过滤器要比ASP.NET MVC中的简单些。然而,这两者是在不同的命名空间中声明的,且是功能独立的。特别是MVC中使用的HandleErrorAttribute类不会处理Web API控制器中抛出的异常。

Here is a filter that converts NotImplementedException exceptions into HTTP status code 501, Not Implemented:
以下是将NotImplementedException异常转换成HTTP状态码“501 — 未实现”的一个过滤器:

namespace ProductStore.Filters { using System; using System.Net; using System.Net.Http; using System.Web.Http.Filters; public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is NotImplementedException) { context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); } } } }

The Response property of the HttpActionExecutedContext object contains the HTTP response message that will be sent to the client.
HttpActionExecutedContext对象的Response属性含有将发送给客户端的HTTP响应消息。

Registering Exception Filters
注册异常过滤器

There are several ways to register a Web API exception filter:
以下是注册Web API异常过滤器的几种方式:

By action
由动作注册

By controller
由控制器注册

Globally
全局注册

To apply the filter to a specific action, add the filter as an attribute to the action:
要把过滤运用于特定的动作,在动作上添加该过滤器的注解属性: