Asp.Net Web API(四)
HttpResponseException-----HTTP响应异常
如果Web API控制器抛出一个未捕捉的异常,会发生什么呢?在默认情况下,大多数异常都会转换为一个带有状态码500的内部服务器错误的HTTP响应。
这个HTTPResponseException类型是一个特殊的类型。这种异常会返回你在异常构造器中指定的任何HTTP状态码。例如,在以下方法中,如果这个id参数无效,那么会返回“404---未找到”
public Product GetProduct(int id)
{
var item = repository.Get(id);
if (item == null)
//未找到返回一个404的状态码
throw new HttpResponseException(HttpStatusCode.NotFound);
return item;
}
为了响应进行更多的控制,你也可以构造整个响应消息,并用HTTPResponseMessage来包含它:
public Product GetProduct(int id)
{
var item = repository.Get(id);
if (item == null)
//未找到返回一个404的状态码
{
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---异常过滤器
通过编写一个异常过滤器,你可以定制Web API如何处理异常。当一个控制器抛出一个未处理异常,且这个异常不是一个HttpResponseException异常时,一个异常过滤器会被执行。HttpResponseException类型是一个特殊情况,因为它是专门设计用来返回一个HTTP响应的。
异常过滤器实现System.Web.Http.Filters.IExceptionFilter接口。编写异常过滤器最简单的方法是通过System.Web.Fitlers.ExceptionFilterAttribute类进行派生,并重写OnException方法。
注意:ASP.NET Web API中的异常过滤器与ASP.NET MVC中是及其相似的。然后,它们被声明在不用的命名空间下,且功能也是独立的。特别强调以下,ASP.NET MVC中使用的HandlerErrorFilterAttribute不会处理Web API控制器抛出的异常。
以下是将NotImplementedException异常转换成HTTP状态码“501 - 未实现”的过滤器:
namespace WebAPIDemo.Filter
{
public class NotImpleExceptionFilterAttribute:ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception is NotImplementedException)
actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.NotImplemented);
}
}
}
HttpActionExecutedContext对象的Response属性含有发送到客户端的HTTP响应消息
Registering Exception Filters --- 注册异常过滤器
以下是注册Web API异常过滤器的几种方式
1.通过Action注册
2.通过Controller注册
3.通过全局注册
要把过滤器应用特定的Action,在Action中添加过滤器的注解属性
[NotImpleExceptionFilter]
public Product GetProduct(int id)
{
var item = repository.Get(id);
if (item == null)
//未找到返回一个404的状态码
{
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;
}
要把过滤器应用于一个控制器的所有Action,可以在Controller上添加过滤器的注解属性
[NotImpleExceptionFilter]
public class ProductController : ApiController
{
}
要全局性的把过滤器运用于所有的Web API控制器将该过滤器的一个实例添加GlobalConfiguration.Configuration.Filter集合。这个集合中的所有异常过滤器会应用于任何Web API控制器Action
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//注册全局异常过滤器
GlobalConfiguration.Configuration.Filters.Add(new NotImpleExceptionFilterAttribute());
}
}
HttpError----HTTP错误
HttpError对象为在响应正文中返回错误消息提供了响应的方法。以下实例演示了如何用HttpError在响应中返回HTTP状态码“404--未找到”:
public HttpResponseMessage GetProduct(int id)
{
var item = repository.Get(id);
if (item != null)
return Request.CreateResponse(HttpStatusCode.OK, item);
var message = string.Format("Product with id = {0} not found", id);
HttpError httpError = new HttpError(message);
return Request.CreateResponse(HttpStatusCode.NotFound, httpError);
}
在这个例子中,如果该方法成功,它会在HTTP响应中返回产品。但如果所请求的产品未找到,则HTTP响应会在请求体中包含一个HttpError。该响应看起来大致像这样
HTTP/1.1 Not Found
Content-Type: application/json; charset=utf-
Date: Thu, Aug :: GMT
Content-Length: {
"Message": "Product with id = 12 not found"
}
注意。在这个例子中,HttpError会被序列化成JSON。使用HttpError的一个好处是,与其它强类型模型一样,会进行同样的“content-negotiation”(暂未实现)和序列过程
直接替代创建HttpError对象的一种方法是:你可以使用CreateErrorResponse方法:
public HttpResponseMessage GetProduct(int id)
{
var item = repository.Get(id);
if (item != null)
return Request.CreateResponse(HttpStatusCode.OK, item);
var message = string.Format("Product with id = {0} not found", id);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
CreateErrorResponse在System.Net.Http.HttpRequsetMessageExtensions类中被定义的一个扩展方法。本质上,CreateErrorResponse会创建一个HttpError实例,然后创建一个包含该HttpError的HttpResponseMessage
Adding Custom Key-Values to HttpError 把自定义的键值添加到HttpError
HttpError类实际上是个键--值集合,(派生与于Dictionary<String,Object>),因此你可以添加自己的键--值对
public HttpResponseMessage GetProduct(int id)
{
var item = repository.Get(id);
if (item != null)
return Request.CreateResponse(HttpStatusCode.OK, item);
var message = string.Format("Product with id = {0} not found", id);
var err = new HttpError(message);
err["error_sub_code"] = ;
return Request.CreateErrorResponse(HttpStatusCode.NotFound, err);
}
Using HttpError with HttpResponseException以HttpResponseException的方式来使用HttpError
前面的例子是从Action返回一个HttpResponseMessage消息,但你也可以使用HttpResponseException来返回一个HttpError。这让你能够在正常成功情况下返回强类型模型,而在错误时,仍返回HttpError
public Product GetProduct(int id)
{
var item = repository.Get(id);
if (item != null)
return item;
var message = string.Format("Product with id = {0} not found", id);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
}
Asp.Net Web API(四)的更多相关文章
- Asp.Net Web API 2第十四课——Content Negotiation(内容协商)
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...
- Asp.Net Web API 2第四课——HttpClient消息处理器
Asp.Net Web API 导航 Asp.Net Web API第一课:入门http://www.cnblogs.com/aehyok/p/3432158.html Asp.Net Web A ...
- 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用
由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...
- ASP.NET Web API Model-ModelMetadata
ASP.NET Web API Model-ModelMetadata 前言 前面的几个篇幅主要围绕控制器的执行过程,奈何执行过程中包含的知识点太庞大了,只能一部分一部分的去讲解,在上两篇中我们看到在 ...
- ASP.NET Web API 过滤器创建、执行过程(二)
ASP.NET Web API 过滤器创建.执行过程(二) 前言 前面一篇中讲解了过滤器执行之前的创建,通过实现IFilterProvider注册到当前的HttpConfiguration里的服务容器 ...
- How ASP.NET Web API 2.0 Works?[持续更新中…]
一.概述 RESTful Web API [Web标准篇]RESTful Web API [设计篇] 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用 二.路由 ...
- 初试ASP.NET Web API/MVC API(附Demo)
写在前面 HTTP RESTful 创建Web API 调用Web API 运行截图及Demo下载 ASP.NET Web API是一个框架,可以很容易构建达成了广泛的HTTP服务客户端,包括浏览 ...
- ASP.NET Web API路由系统:路由系统的几个核心类型
虽然ASP.NET Web API框架采用与ASP.NET MVC框架类似的管道式设计,但是ASP.NET Web API管道的核心部分(定义在程序集System.Web.Http.dll中)已经移除 ...
- ASP.NET Web API路由系统:Web Host下的URL路由
ASP.NET Web API提供了一个独立于执行环境的抽象化的HTTP请求处理管道,而ASP.NET Web API自身的路由系统也不依赖于ASP.NET路由系统,所以它可以采用不同的寄宿方式运行于 ...
随机推荐
- SSM所需的jar
首先去找struts的. http://struts.apache.org/ 下载最新的struts 2.3.7. http://www.springsource.org/spring-framewo ...
- 微信小程序开发《三》:微信小程序请求不能使用session的原因及解决办法
本人在前面的微信小程序开发<二>中提到要想在服务端保持状态需要在客户端第一次请求服务器的时候给客户端返回一个sessionid,由客户端在本地保存,下次请求的时候在header里面带上这个 ...
- spring4新特性-泛型依赖注入
1 文件结构 2 具体类 2.1两个抽象类,在Service里面写公共的方法,在各自的具体实现类里面写各自的方法 package repo;import model.User;/** * Crea ...
- linux配置远程Git仓库
一,安装git yum install git 二,在服务器(119.28.1.1)目录( /git/admin )上创建一个仓库 cd /git/admin touch aaa.html git i ...
- org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.Integer
使用hibernate时,在save方法时,报了:org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.In ...
- 25个Java机器学习工具和库
本列表总结了25个Java机器学习工具&库: 1. Weka集成了数据挖掘工作的机器学习算法.这些算法可以直接应用于一个数据集上或者你可以自己编写代码来调用.Weka包括一系列的工具,如数据预 ...
- (五)solr7.1.0之solrJ的使用
(五)solr7.1.0之solrJ的使用 下面是solr7的官网API介绍: 网页翻译的不是很准确,只能了解个大概,基本能获取如下信息: 一.构建和运行SolrJ应用程序 对于用Maven构建的项目 ...
- TFboy养成记
转自:http://www.cnblogs.com/likethanlove/p/6547405.html 在tensorflow的使用中,经常会使用tf.reduce_mean,tf.reduce_ ...
- input type="radio" 赋值问题
之前项目中 后台传值 然后赋给单选input 在网上找了好久,现在有时间了,整理一下 ,方便以后有人会用到. $('radio[name="sex"][value'" ...
- windows 下更新 npm 和 node
原文链接 公司的新项目要启动了,需要使用 Angular 4.0,并且使用 webpack 工具进行打包.所以就需要安装 node.node 的安装很简单,在 node 的官网 nodejs.org ...