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

在 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 的操作方式。 www.it165.net


HttpResponseMessage

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

public HttpResponseMessage DeleteProductById(int id)
{
      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;
}

如果需要响应列举对象可以使用 ObjectContent<T>,如下

public HttpResponseMessage GetAllProducts()
{
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

    response.Content = new ObjectContent<IEnumerable<product>>(new ProductDao().GetProducts(),new JsonMediaTypeFormatter());
    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);
  } }
 
原文地址:https://www.cnblogs.com/weixing/p/8204554.html