3 c# asp.net-mvc caching http-headers asp.net-web-api
鉴于以下内容:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
和:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
我见过两种编码风格.一个使用例外,另一个不使用.一个使用CreateResponse <>和另一个CreateResponse().有人能说出使用这些有什么优点/缺点吗?据我所知,第二种方法似乎看起来更完整但是真的需要使用try/catch来做这么简单的事情吗?
Mik*_*son 11
抛出的主要好处HttpResponseException是当你的action方法返回一个模型类型而不是一个HttpResponseMessage.例如:
public Product Get(int id)
{
Product p = _GetProduct(id);
if (p == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return p;
}
Run Code Online (Sandbox Code Playgroud)
这相当于以下内容:
public HttpResponseMessage Get(int id)
{
Product p = _GetProduct(id);
if (p == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, p);
}
Run Code Online (Sandbox Code Playgroud)
选择任何一种风格都可以.
您不应该抓住HttpResponseExceptions,因为重点是Web API管道捕获它们并将它们转换为HTTP响应.在您的第二个代码示例中,当您确实希望客户端接收Not Found(404)时,Not Found错误会被捕获并变为Bad Request错误.
更长的回答:
CreateResponsevs CreateResponse<T>与使用无关HttpResponseException.
CreateResponse 返回没有邮件正文的HTTP响应:
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
Run Code Online (Sandbox Code Playgroud)
CreateResponse<T> 获取类型为T的对象并将该对象写入HTTP响应的主体:
public HttpResponseMessage Get()
{
Product product = new Product();
// Serialize product in the response body
return Request.CreateResponse<Product>(HttpStatusCode.OK, product);
}
Run Code Online (Sandbox Code Playgroud)
下一个示例完全相同,但使用类型推断省略泛型类型参数:
public HttpResponseMessage Get()
{
Product product = new Product();
// Serialize product in the response body
return Request.CreateResponse(HttpStatusCode.OK, product);
}
Run Code Online (Sandbox Code Playgroud)
该CreateErrorResponse方法创建一个HTTP响应,其响应主体是一个HttpError对象.这里的想法是使用通用消息格式进行错误响应.通话CreateErrorResponse与此基本相同:
HttpError err = new HttpError( ... )
// Serialize err in the response.
return Request.CreateResponse(HttpStatusCode.BadRequest, err);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5991 次 |
| 最近记录: |