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. Openmeetings 3.1.1 报错-Internal error

    安装手册官网教程:安装:我按照文档安装了至少10次,都是在初始化数据库时出现了如下:Internal error (图已失效) 后面找了N多资料都没有解决问题直到联Installation OpenM ...

  2. [转]PHP Session的一个警告

    警告全文如下: PHP Warning: Unknown: Your script possibly relies on a session side-effect which existed unt ...

  3. Changing SID Server 2012

    Changing SID Server 2012  Windows Server > Windows Server 2012 General Question 0 Sign in to vote ...

  4. 支持Cookie并开放了一些特殊设置项的HttpWebClient

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.N ...

  5. Linux环境下SVN服务器端的安装与配置

    最近尝试了下在Linux(CentOS6.5)环境下安装与配置SVN服务器端,安装过程中碰到了一些问题,参看了网友们分享的一些心得,并通过自己实际的操作,最终安装与配置成功!总的来说网上的说法芸芸,大 ...

  6. java基础-servlet-1

    servlet,是运行于服务器端的小程序.它既可以运行在http服务器端,也可以运行在mail等其他服务器端.我是这样理解,tomcat把接收到的客户端请求,转发给servlet,它负责业务处理,并且 ...

  7. 如何用CSS实现在新窗口打开链接?

    *如何用CSS实现在新窗口打开链接? <style type="text/css"> <!-- .target2 a:active {test:expressio ...

  8. SpringMvc JSON 406,吐血。。。。

    解决方法一: 1.导入jackson-core-2.5.1.jar和jackson-databind-2.5.1.jar 2.Spring配置文件添加: 1 spring3为:org.springfr ...

  9. WinRAR压缩操作帮助类

    //------------------------------------------------------------------------------------- // All Right ...

  10. GDB 调试遇到??的问题

    今天总算解决了一个大的bug,爽! 我的程序crash,有了coredump文件,在Linux PC上用arm-linux-gdb debug it. The result is: #0  0x402 ...