[英]Should I return a status code or throw an exception in .Net Web Api 2
I have seen examples like this 我曾见过这样的例子这
public IHttpActionResult GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Ok(item);
}
But I have also imagine this is an option 但我也想象这是一个选择
public IHttpActionResult GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
Is there an advantage to throwing an exception or simply returning a NotFound (IHttpActionResult instance)? 抛出异常或只返回NotFound(IHttpActionResult实例)是否有优势?
I know there are stages in the response / request pipeline where either of these results can be handled, like this for the first example 我知道响应/请求管道中有一些阶段可以处理这些结果中的任何一个,就像第一个例子中的那样
public class NotFoundExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotFoundException)
{
// Do some custom stuff here ...
context.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
}
...
GlobalConfiguration.Configuration.Filters.Add(
new ProductStore.NotFoundExceptionFilterAttribute());
The IHttpActionResult
is a feature that was added in WebApi 2. The traditional methods from WebApi 1, ie creating an HttpResponseMessage
or throwing an HttpResponseException
, are still available to you, but the IHttpActionResult
was developed to streamline the process. IHttpActionResult
是WebApi 2中添加的一项功能。来自WebApi 1的传统方法,即创建HttpResponseMessage
或抛出HttpResponseException
,仍然可用,但IHttpActionResult
开发是为了简化流程。
The IHttpActionResult
Interface has one method: IHttpActionResult
接口有一个方法:
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
The NotFound
method simply creates a NotFoundResult
which returns an empty response with HttpStatusCode.NotFound
. NotFound
方法只是创建一个NotFoundResult
,它返回一个带有HttpStatusCode.NotFound
的空响应。 This is essentially the exact same thing that throwing HttpResponseException(HttpStatusCode.NotFound)
does, but in a more uniform syntax. 这与抛出HttpResponseException(HttpStatusCode.NotFound)
完全相同,但语法更统一。
The IHttpActionResult
interface also allows you to easily create custom ActionResult
classes to return any HttpStatusCode
or any content type you wish. IHttpActionResult
接口还允许您轻松创建自定义ActionResult
类,以返回任何HttpStatusCode
或您希望的任何内容类型。
Throwing an exception is always should be considered as an exceptional case. 抛出异常始终应被视为例外情况。 While being rare, it still can happen and should be handled properly. 虽然很少见,但它仍然可以发生,应该妥善处理。
It depends on how often do you need to retrieve nonexistent items from your database. 这取决于您需要从数据库中检索不存在的项目的频率。 Keep in mind that often exception throwing is always a performance killer. 请记住,异常抛掷通常是性能杀手。
You should also look into this: 您还应该研究一下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.