Web API 中提供了 HttpResponseMessage 与 HttpResponseException 用于处理返回讯息,HttpResponseMessage 用于返回一个来自于客户端的请求结果讯息,你可以使用 HttpResponseMessage 自订返回的内容,HttpResponseException 则是以当发生例外时用来返回客户端错误讯息,例如一个 404 或 500 错误。

其实用 HttpResponseMessage 也能够返回 404、500 等错误,那为何还需要使用 HttpResponseException 来返回错误? 参考此文章 提出了一个观点,文章中提到当呼叫 Web API 服务时发生了与预期上不同的错误时,理当应该中止程序返回错误讯息,这时对于错误的返回就该使用 HttpResponseException,而使用 HttpResponseMessage 则是代表着当客户端发送了一个工作请求而 Web API 正确的完成了这个工作,就能够使用 HttpResponseMessage 返回一个 201 的讯息,所以 HttpResponseMessage 与 HttpResponseException 在使用上根本的目标就是不同的,用 HttpResponseMessage 去返回一个例外错误也会让程序结构难以辨别且不够清晰,接着让我们看一下 HttpResponseMessage 与 HttpResponseException 的操作方式。

HttpResponseMessage

  HttpResonseMessage 用来响应讯息并包含状态码及数据内容,如需要返回一个 HttpResonseMessage 的实例可以使用 Request 的扩充功能 CreateResponse 方法,如下

public HttpResponseMessage DeleteProductById(int id)
{
// do something...
return Request.CreateResponse(HttpStatusCode.OK);
}

当然也可以自行定义响应的状态码及数据内容,如下

public HttpResponseMessage DeleteProductById(int id)
{
// do something...
var response = Request.CreateResponse(HttpStatusCode.OK);
response.StatusCode = HttpStatusCode.OK;
response.Content = new StringContent("Delete Success!");
// 响应内容
return response;
}

另外 CreateResponse 扩充方法也提供了 CreateResponse<T> 泛型的回应方法 ,如下

public HttpResponseMessage GetProductById(int id)
{
IEnumerable<product> products = new ProductDao().GetProducts();
var product = products.Where(p => p.Id == id);
if (product.FirstOrDefault<product>() != null)
return Request.CreateResponse<Product>(HttpStatusCode.OK, product.First<Product>());
else
throw new HttpResponseException(HttpStatusCode.NotFound);
}

HttpResponseException

  HttpResponseException 为处理例外之用,能够将指定的 HttpResponseMessage 返回至客户端,在客户端呼叫 Web API 发生错误时,客户端并不会得到一个空值或错误画面,故需要将错误包装成回复讯息而最基本的情况下可以只回复状态码,如下。

public HttpResponseMessage GetAllProducts()
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}

当然也能够自己定义错误讯息内容,如下

 public HttpResponseMessage PutProduct(int id, string name, string category, string price, int stock)
{
ProductDao productDao = new ProductDao(); if (productDao.UpdateProduct(id, name, category, price, stock))
return Request.CreateResponse(HttpStatusCode.OK);
else
{
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Update Product Error"),
ReasonPhrase = "Server Error"
};
throw new HttpResponseException(response);
}
}

HttpResponseMessage和HttpResponseException (转)的更多相关文章

  1. Web API使用HttpResponseMessage与HttpResponseException的差异 HttpResponseMessage 返回类型

    在 Web API 中提供了 HttpResponseMessage 与 HttpResponseException 用于处理返回讯息,HttpResponseMessage 用于返回一个来自于客户端 ...

  2. C#进阶系列——WebApi 异常处理解决方案

    前言:上篇C#进阶系列——WebApi接口传参不再困惑:传参详解介绍了WebApi参数的传递,这篇来看看WebApi里面异常的处理.关于异常处理,作为程序员的我们肯定不陌生,记得在介绍 AOP 的时候 ...

  3. WebApi异常

    WebApi异常处理解决方案   前言:上篇C#进阶系列——WebApi接口传参不再困惑:传参详解介绍了WebApi参数的传递,这篇来看看WebApi里面异常的处理.关于异常处理,作为程序员的我们肯定 ...

  4. (转)C# WebApi 异常处理解决方案

    原文地址:http://www.cnblogs.com/landeanfen/p/5363846.html 一.使用异常筛选器捕获所有异常 我们知道,一般情况下,WebApi作为服务使用,每次客户端发 ...

  5. C#进阶系列——WebApi 异常处理解决方案(转)

    出处:http://www.cnblogs.com/landeanfen/p/5363846.html 阅读目录 一.使用异常筛选器捕获所有异常 二.HttpResponseException自定义异 ...

  6. C#进阶系列——WebApi异常处理解决方案

    阅读目录 一.使用异常筛选器捕获所有异常 二.HttpResponseException自定义异常信息 三.返回HttpError 四.总结 正文 为什么说是实践?因为在http://www.asp. ...

  7. ASP.NET Web API 异常处理 HttpResponseException 以及Angularjs获取异常信息并提示

    一.HttpResponseException 如果一个Web API控制器抛出一个未捕捉异常,默认地,大多数异常都会被转化成一个带有状态码“500 – 内部服务器错误”的HTTP响应.HttpRes ...

  8. WebAPI 抛出HttpResponseException异常

    [HttpGet] public List<UserInfo> GetList() { try { List<UserInfo> list = new List<User ...

  9. ASP.NET 5 WebApi 返回 HttpResponseMessage

    首先,ASP.NET 5 没有了 MVC 和 WebApi 的区分,都属于 ASP.NET 5,从 Controller 的继承就可以看出,原来 ASP.NET WebApi 2 ValuesCont ...

随机推荐

  1. java mongoDB 二级数组嵌套查询

    场景: 会员集合下有多个会员文档,会员文档下有多个订单文档,订单买了多个商品文档 member->orders>orderItems 要求: 通过会员id和商品id验证会员是否购买过该商品 ...

  2. python print 进度条的例子

    def progress(width, percent): print "%s %d%%\r" % (('%%-%ds' % width) % (width * percent / ...

  3. STM32 硬件I2C 到底是不是个坑?

    /** ****************************************************************************** * @author    Maox ...

  4. LeetCode "Arranging Coins"

    A simple math.. take care of data overflow though. class Solution { public: int arrangeCoins(int n) ...

  5. Java多线程系列- DelayQueue延时队列

    我们在开发中,有如下场景 a) 关闭空闲连接.服务器中,有很多客户端的连接,空闲一段时间之后需要关闭之.b) 缓存.缓存中的对象,超过了空闲时间,需要从缓存中移出.c) 任务超时处理.在网络协议滑动窗 ...

  6. linux下对进程按照内存使用情况进行排序

    linux下对进程按照内存使用情况进行排序的命令为:ps aux --sort -rss 详细解说参见 http://alvinalexander.com/linux/unix-linux-proce ...

  7. oracle中找出某个字段中有非数字型的记录

    工作中遇到一个大表记录中有非法非数字字符,不想用正则语法去做, 用一条SQL语句查出来的方法如下: select * from table where translate(col,'*01234567 ...

  8. vue.js 1中父组件跳到子组件中并传参让子组件显示不同的内容

    父组件中的点击跳转: <ul class="insurance-entry clearfloat"> <li v-link="{name:'produc ...

  9. 由system.currentTimeMillis() 获得当前的时间

    System类代表系统,系统级的很多属性和控制方法都放置在该类的内部.该类位于java.lang包. currentTimeMillis方法 public static long currentTim ...

  10. Unity3D 第一人称控制器 C#脚本

    CharacterMotor.cs using UnityEngine; using System.Collections; /** * @Author : www.xuanyusong.com */ ...