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. python 发邮件-带附件-文本-html

    #!/usr/bin/python # encoding=utf-8 # Filename: send_email.py from email.mime.image import MIMEImage ...

  2. DB2 中文排序问题

    本地测试库中 代码集: GBK 数据库配置发行版级别 = 0x0c00 数据库发行版级别 = 0x0c00 数据库地域 = CN 数据库代码页 = 1386 数据库代码集 = GBK 数据库国家/地区 ...

  3. HTML meta 头部的一些内容

    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable= ...

  4. 虚幻4外包团队-推荐非常全面的的Unreal教程

    <Unreal SDK 游戏开发从入门到精通(UnrealScript语法.UI Scene界面.UDK独立开发游戏)> 课程讲师:Shark  课程分类:.net 适合人群:初级 课时数 ...

  5. C#实现对Windows 服务安装

    Windows服务作用:定时用户消息推送,WEB程序实时统计等 Windows服务创建:C#创建服务的方式也有很多种,建议大家在做之前可以先全面了解一下这方面东西再去动手这样便于解决中间遇到一些比较棘 ...

  6. Katana

    - KAT101 - Katana has many nodes for operation, e.g. MaterialAssign, - The connections between nodes ...

  7. 基于Three.js的360X180度全景图预览插件

    基于Three.js的360X180度全景图预览插件 时间 2015-08-12 10:01:10  HTML5中国 原文  http://www.html5cn.org/article-8621-1 ...

  8. 微信开发-ACCESS TOKEN 过期失效解决方案

    微信开发-ACCESS TOKEN 过期失效解决方案 起因:因为access_token的重要性,开发过微信的都知道,但是他有自己的生命周期,官方解释为:"有效期为7200秒",一 ...

  9. sql server 替换特殊符号

    --create-- 去掉特殊符号alter function RepSymbol(@str nvarchar(max))returns nvarchar(max)as begin set @str= ...

  10. 每天一个 Linux 命令(18):locate 命令

    locate 让使用者可以很快速的搜寻档案系统内是否有指定的档案.其方法是先建立一个包括系统内所有档案名称及路径的数据库,之后当寻找时就只需查询这个数据库,而不必实际深入档案系统之中了.在一般的 di ...