CreateResponse() 和 CreateResponse() 与 Web API 有什么区别

本文关键字:CreateResponse API 区别 什么 Web Content | 更新日期: 2023-09-27 18:36:34

给定以下内容:

    [HttpGet]
    [ActionName("GetContent")]
    public HttpResponseMessage GetContent(int id)
    {
        Content content = _uow.Contents.GetById(id);
        if (content == null)
        {
            var message = string.Format("Content with id = {0} not found", id);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, content);
        }
    }

和:

    [HttpGet]
    [ActionName("GetContent")]
    public HttpResponseMessage GetContent(int id)
    {
        try
        {
            Content content = _uow.Contents.GetById(id);
            if (content == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            return Request.CreateResponse<Content>(HttpStatusCode.OK, content);
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        } 
    }

我见过两种编码风格。一个使用例外,另一个不使用。一个使用 CreateResponse<>另一个使用 CreateResponse()。有人可以说出使用这些的优点/缺点是什么吗?据我所知,第二种方法似乎看起来更完整,但是真的需要对这样简单的事情使用try/catch吗?

CreateResponse<Content>() 和 CreateResponse() 与 Web API 有什么区别

HttpResponseException的主要好处是当您的操作方法返回模型类型而不是HttpResponseMessage时。例如:

public Product Get(int id) 
{
    Product p = _GetProduct(id);
    if (p == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return p;
}

这等效于以下内容:

public HttpResponseMessage Get(int id) 
{
    Product p = _GetProduct(id);
    if (p == null)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound);
    }
    return Request.CreateResponse(HttpStatusCode.OK, p);
}

可以选择任何一种样式。

不应捕获HttpResponseException,因为重点是 Web API 管道捕获它们并将其转换为 HTTP 响应。在第二个代码示例中,当您确实希望客户端收到未找到 (404) 时,将捕获"未找到"错误请求错误并将其转换为错误请求错误。

更长的答案:

CreateResponse vs CreateResponse<T> 与使用HttpResponseException无关。

CreateResponse返回一个没有消息正文的 HTTP 响应:

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.NotFound);
}

CreateResponse<T> 获取 T 类型的对象并将该对象写入 HTTP 响应的正文中:

public HttpResponseMessage Get()
{
    Product product = new Product();
    // Serialize product in the response body
    return Request.CreateResponse<Product>(HttpStatusCode.OK, product);  
}

下一个示例完全相同,但使用类型推断来省略泛型类型参数:

public HttpResponseMessage Get()
{
    Product product = new Product();
    // Serialize product in the response body
    return Request.CreateResponse(HttpStatusCode.OK, product);  
}

CreateErrorResponse方法创建一个 HTTP 响应,其响应正文是 HttpError 对象。这里的想法是使用通用的消息格式进行错误响应。调用CreateErrorResponse基本上与此相同:

HttpError err = new HttpError( ... )
// Serialize err in the response.
return Request.CreateResponse(HttpStatusCode.BadRequest, err);