原文链接:https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling


本文介绍了在 ASP.NET Web API 中的错误和异常处理

  • HttpResponseException
  • Exception Filters
  • Registering Exception Filters
  • HttpError

HttpResponseMessage

如果一个 Web API 控制器抛出一个未处理的异常会发生什么?默认情况,大多数异常会被转换为 HTTP 响应,状态码为500(服务器内部错误)。

HttpResponseMessage 类型是一种特殊情况。该异常返回异常构造函数中指定的任何 HTTP 状态码。例如,以下方法中如果 id 无效,则返回 404(找不到指定的资源)。

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

为了更好地控制响应,您还可以构造整个响应消息,并将其与 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;
}

异常过滤器

你可以通过写一个 异常过滤器 来自定义 Web API 如何处理异常。 当一个控制器抛出一个未处理异常时,异常过滤器就会执行 ---- 而这并不是一个 HttpResponseException 异常。 HttpResponseException 类型是一种特殊情况,因为它专门用于返回 HTTP 响应。

ASP.NET Web API 中的异常过滤器和 ASP.NET MVC 中的异常过滤器很相似。但是,但是,它们分别声明在单独的命名空间和函数中。特别地,MVC中使用的HandleErrorAttribute 类不处理 Web API 控制器抛出的异常。

这里有一个过滤器,将**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);
}
}
}
}

**HttpActionExecutedContext ** 对象的 **Response **属性包含将被发送给客户端的响应消息。

注册异常过滤器

有集中方法注册 Web API 异常过滤器:

  • 通过 Action
  • 通过 Controller
  • 全局

为指定的 Action 应用过滤器:

public class ProductsController : ApiController
{
[NotImplExceptionFilter]
public Contact GetContact(int id)
{
throw new NotImplementedException("This method is not implemented");
}
}

为 Controller 的所有 Action应用过滤器:

[NotImplExceptionFilter]
public class ProductsController : ApiController
{
// ...
}

为全局所有的 Web API Controller 应用过滤器,要在 GlobalConfiguration.Configuration.Filters 集合中添加一个过滤器实例。 在这个集合中的异常过滤器应用到任何 Web API Controller 的 Action:

GlobalConfiguration.Configuration.Filters.Add(
new ProductStore.NotImplExceptionFilterAttribute());

如果你是用 "ASP.NET MVC 4 Web Application" 项目模版创建的项目,把 Web API 配置代码放在 WebApiConfig 类中,该类位于 App_Start 文件夹里:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute()); // Other configuration code...
}
}

HttpError

HttpError 对象提供了一种在响应正文中返回错误信息的一致方法。以下示例显示如何在响应正文中返回HttpError的HTTP状态代码404(找不到)。

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 是 System.Net.Http.HttpRequestMessageExtensions 类的一个扩展方法,在内部 CreateErrorResponse 构建一个 HttpError 实例,然后创建一个包含 HttpError 的 **HttpResponseMessage **。

在下面例子中,如果方法成功将在 HTTP 响应中返回产品。但是如果请求的产品没有被找到,那么 HTTP 响应的请求体里就包含一个 HttpError。这个示例可能雷类似下面这样:

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"
}

注意到在这个示例中 HttpError 被序列化成 JSON。 使用 HttpError 的一个优点是,它经历了与任何其他强类型模型相同的内容协商和序列化过程。

HttpError and Model Validation

对模型验证来说,你可以把模型状态传给 CreateErrorResponse ,将会在响应中包含验证错误消息:

public HttpResponseMessage PostProduct(Product item)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
} // Implementation not shown...
}

这个示例可能返回以下响应:

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."
]
}
}

更多关于模型绑定的信息,请参见Model Validation in ASP.NET Web API。

和 HttpResponseException 一起使用 HttpError

前面的示例,从控制器的 Action 返回一个 HttpResponseMessage ,但是你也可以使用 **HttpResponseException ** 返回一个 HttpError。 这允许在正常的成功情况下返回强类型模型,而如果有错误,仍然返回 HttpError。

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;
}
}

[翻译] ASP.NET WebAPI 中的异常处理的更多相关文章

  1. 关于ASP.NET WebAPI中HTTP模型的相关思考

    对于.NET的分布式应用开发,可以供我们选择的技术和框架比较多,例如webservice,.net remoting,MSMQ,WCF等等技术.对于这些技术很多人都不会陌生,即时没有深入的了解,但是肯 ...

  2. 在ASP.NET WebAPI 中使用缓存【Redis】

    初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutpu ...

  3. 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

    一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...

  4. Asp.Net WebAPI 中Cookie 获取操作方式

    1. /// <summary> /// 获取上下文中的cookie /// </summary> /// <returns></returns> [H ...

  5. Asp.Net WebAPI中Filter过滤器的使用以及执行顺序

    转发自:http://www.cnblogs.com/UliiAn/p/5402146.html 在WEB Api中,引入了面向切面编程(AOP)的思想,在某些特定的位置可以插入特定的Filter进行 ...

  6. ASP.NET WebApi 中使用swagger 构建在线帮助文档

    1 在Visual Studio 中创建一个Asp.NET  WebApi 项目,项目名:Com.App.SysApi(本例创建的是 .net 4.5 框架程序) 2  打开Nuget 包管理软件,查 ...

  7. [转]在ASP.NET WebAPI 中使用缓存【Redis】

    初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutpu ...

  8. ASP.Net WebAPI中添加helppage帮助页面

    一.自动创建带帮助的WebAPI 1.首先创建项目的时候选择WebAPI,如下图所示,生成的项目会自动生成帮助文档. 2.设置调用XML文档的代码 3.设置项目注释XML文档生成目录,项目——属性—— ...

  9. 动态类型和匿名类型在asp.net webapi中的应用

    1.  动态类型用于webapi调用 假设需要调用一个webapi,webapi返回了一个json字符串.字符串如下: {"ProductId":"AN002501&qu ...

随机推荐

  1. 编程学习笔记(第三篇)面向对象技术高级课程:绪论-软件开发方法的演化与最新趋势(3)软件开发的现状、UML扩展

    一.软件开发的现状 软件领域正在发生一个巨变,特别是近几年来,软件领域正在发生翻天覆地的变化. 这一变化主要以这个云 + 端大数据, 这些是随着目前最先进的一些技术的产生而产生的. 随着这些新的技术以 ...

  2. maven3 学习

    主要参考博文:http://www.cnblogs.com/yjmyzz/p/3495762.html 修正: 1.下载maven 3.1.1 先到官网http://maven.apache.org/ ...

  3. MS SQMServer2008R2 连接不到远程服务的解决办法

    问题: MS SQMServer2008R2 连接不到远程服务的解决办法.程序提示的错误如下: [2017/02/19 17:46:21] 在与 SQL Server 建立连接时出现与网络相关的或特定 ...

  4. 【Web】Nginx Rewrite规则

    Rewrite介绍 Rewrite主要的功能就是实现URL的重写,Nginx的Rewrite规则采用Pcre,perl兼容正则表达式的语法规则匹配,如果需要Nginx的Rewrite功能,在编译Ngi ...

  5. GUI的最终选择Tkinter模块练习篇

    一.Canvas画布练习 1)简单的绘制图框 from tkinter import * # 构建一个窗口 tk = Tk() # 画布 canvas= Canvas(tk,width=,height ...

  6. 746. Min Cost Climbing Stairs

    两种方法,核心思想都一样,求出走到每一步上的最小开销,直到最后一步和倒数第二步,比较其最小值返回即可. 方法一,用一个辅助的容器 class Solution { public: int minCos ...

  7. nginx 502 Bad Gateway 错误解决办法

    nginx出现502有很多原因,但大部分原因可以归结为资源数量不够用,也就是说后端PHP-fpm处理有问题,nginx将正确的客户端请求发给了后端的php-fpm进程,但是因为php-fpm进程的问题 ...

  8. Win7 VS2013环境编译Squirrel 3.0.7

    Squirrel是一个类似Lua,但是更面向对象的脚本语言. 国内这个介绍很少,环境配置更是没有任何文章提到,花了点时间搞定了,备忘记录下过程. 首先是下载,写本文时Squirrel最新版本为3.0. ...

  9. 【终极答案】搭建selenium3.11 +Firefox+python3.6自动化UI测试环境踩的坑

    1 运行之后,出现如下报错 Selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs ...

  10. 容器,表格 ,div,元素可左右拖动,滚动 css

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...