码迷,mamicode.com
首页 > Web开发 > 详细

HttpResponseMessage和HttpResponseException (转)

时间:2016-01-13 10:50:45      阅读:393      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 1 public HttpResponseMessage PutProduct(int id, string name, string category, string price, int stock)
 2 {
 3     ProductDao productDao = new ProductDao();
 4    
 5         if (productDao.UpdateProduct(id, name, category, price, stock))
 6             return Request.CreateResponse(HttpStatusCode.OK);
 7         else
 8         {
 9             var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
10             {
11                 Content = new StringContent("Update Product Error"),
12                 ReasonPhrase = "Server Error"
13             };
14             throw new HttpResponseException(response);
15         }
16 }

 

HttpResponseMessage和HttpResponseException (转)

标签:

原文地址:http://www.cnblogs.com/suiyi1992/p/5126344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!