Exception Handling in ASP.NET Web API webapi异常处理
原文:http://www.asp.net/web-api/overview/error-handling/exception-handling
This article describes error and exception handling in ASP.NET Web API.
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.
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.
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:
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 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.
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.
Here is a filter that converts NotImplementedException exceptions into HTTP status code 501, Not Implemented:
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.
Registering Exception Filters
There are several ways to register a Web API exception filter:
- By action
- By controller
- Globally
To apply the filter to a specific action, add the filter as an attribute to the action:
public class ProductsController : ApiController
{
[NotImplExceptionFilter]
public Contact GetContact(int id)
{
throw new NotImplementedException("This method is not implemented");
}
}
To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:
[NotImplExceptionFilter]
public class ProductsController : ApiController
{
// ...
}
To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filterscollection. Exeption filters in this collection apply to any Web API controller action.
GlobalConfiguration.Configuration.Filters.Add(
new ProductStore.NotImplExceptionFilterAttribute());
If you use the "ASP.NET MVC 4 Web Application" project template to create your project, put your Web API configuration code inside theWebApiConfig
class, which is located in the App_Start folder:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute()); // Other configuration code...
}
}
HttpError
The HttpError object provides a consistent way to return error information in the response body. The following example shows how to return HTTP status code 404 (Not Found) with an HttpError in the response body.
public HttpResponseMessage GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, item);
}
}
CreateErrorResponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensions class. Internally,CreateErrorResponse creates an HttpError instance and then creates an HttpResponseMessage that contains the HttpError.
In this example, if the method is successful, it returns the product in the HTTP response. But if the requested product is not found, the HTTP response contains an HttpError in the request body. The response might look like the following:
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Aug 2012 23:27:18 GMT
Content-Length: 51 {
"Message": "Product with id = 12 not found"
}
Notice that the HttpError was serialized to JSON in this example. One advantage of using HttpError is that it goes through the samecontent-negotiation and serialization process as any other strongly-typed model.
HttpError and Model Validation
For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response:
public HttpResponseMessage PostProduct(Product item)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
} // Implementation not shown...
}
This example might return the following response:
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 320 {
"Message": "The request is invalid.",
"ModelState": {
"item": [
"Required property 'Name' not found in JSON. Path '', line 1, position 14."
],
"item.Name": [
"The Name field is required."
],
"item.Price": [
"The field Price must be between 0 and 999."
]
}
}
For more information about model validation, see Model Validation in ASP.NET Web API.
Using HttpError with HttpResponseException
The previous examples return an HttpResponseMessage message from the controller action, but you can also use HttpResponseExceptionto return an HttpError. This lets you return a strongly-typed model in the normal success case, while still returning HttpError if there is an error:
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
}
else
{
return item;
}
}
Exception Handling in ASP.NET Web API webapi异常处理的更多相关文章
- Exception Handling in ASP.NET Web API
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErr ...
- Global Error Handling in ASP.NET Web API 2(webapi2 中的全局异常处理)
目前,在Web API中没有简单的方法来记录或处理全局异常(webapi1中).一些未处理的异常可以通过exception filters进行处理,但是有许多情况exception filters无法 ...
- ASP.NET Web API之消息[拦截]处理
标题相当难取,内容也许和您想的不一样,而且网上已经有很多这方面的资料了,我不过是在实践过程中作下记录.废话少说,直接开始. Exception 当服务端抛出未处理异常时,most exceptions ...
- 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理
原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...
- ASP.NET Web API 2中的错误处理
前几天在webapi项目中遇到一个问题:Controller构造函数中抛出异常时全局过滤器捕获不到,于是网搜一把写下这篇博客作为总结. HttpResponseException 通常在WebAPI的 ...
- ASP.NET Web API之消息[拦截]处理(转)
出处:http://www.cnblogs.com/Leo_wl/p/3238719.html 标题相当难取,内容也许和您想的不一样,而且网上已经有很多这方面的资料了,我不过是在实践过程中作下记录.废 ...
- ASP.NET Web API系列教程目录
ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...
- ASP.NET Web API系列教程(目录)(转)
注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...
- [转]ASP.NET Web API系列教程(目录)
本文转自:http://www.cnblogs.com/r01cn/archive/2012/11/11/2765432.html 注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP ...
随机推荐
- JavaScript的由来, 浏览器的20年
在很久以前那时候还没有Yahoo,Google....人们还在用28.8kbit/s的"猫"上网, 用户注册或者登录的时候所有的验证都是在服务器验证的, 如果用户注册的时候用户名或 ...
- Jquery每行最后一个LI边距设为0
下面用的是jquery方法,请加载jquery插件 <script type="text/javascript"> $(function(){ $('#newhouse ...
- Python列表、元组、字典和字符串的常用函数
Python列表.元组.字典和字符串的常用函数 一.列表方法 1.ls.extend(object) 向列表ls中插入object中的每个元素,object可以是字符串,元组和列表(字符串“abc”中 ...
- gene_abundance_estimation
/home/liuhui/bin/trinityrnaseq_r20140413p1/util/support_scripts/get_Trinity_gene_to_trans_map.pl Tri ...
- OPENGGL深度测试
深度测试是为了解决那些在绘图过程中本应该被隐藏的面结果却出现了,例如: 绘图代码中先绘制了一个一个近处的立方体,后绘制了一个远处的立方体,结果在绘制过程中,远处的立方体总是在近处的立方体后绘制,所以在 ...
- win10 1607 密匙
win10 1607 安装密钥 GVLK Core=YTMG3-N6DKC-DKB77-7M9GH-8HVX7 Professional=VK7JG-NPHTM-C97JM-9MPGT-3V66T E ...
- 洛谷P1889 士兵站队
题目描述 在一个划分成网格的操场上, n个士兵散乱地站在网格点上.由整数 坐标 (x,y) 表示.士兵们可以沿网格边上.下左右移动一步,但在同时刻任一网格点上只能有名士兵.按照军官的命令,们要整齐地列 ...
- 主机宝(zhujibao) /a/apps/zhujibao/manager/apps/config/config.php no-password Login Vulnerabilities Based On Default cookie Verification From Default File
catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 主机宝管理程序使用了CodeIgniter框架,要想在CodeIgnit ...
- 最小生成树问题---Prim算法与Kruskal算法实现(MATLAB语言实现)
2015-12-17晚,复习,甚是无聊,阅<复杂网络算法与应用>一书,得知最小生成树问题(Minimum spanning tree)问题.记之. 何为树:连通且不含圈的图称为树. 图T= ...
- 当spring 容器初始化完成后执行某个方法
在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查. 比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出 ...