sea*_*ght 5 c# asp.net exception-handling httpresponse asp.net-web-api2
我曾见过这样的例子这
public IHttpActionResult GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Ok(item);
}
Run Code Online (Sandbox Code Playgroud)
但我也想象这是一个选择
public IHttpActionResult GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
Run Code Online (Sandbox Code Playgroud)
抛出异常或简单地返回 NotFound(IHttpActionResult 实例)是否有优势?
我知道在响应/请求管道中有一些阶段可以处理这些结果中的任何一个,就像第一个例子一样
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());
Run Code Online (Sandbox Code Playgroud)
这IHttpActionResult是 WebApi 2 中添加的一项功能。WebApi 1 中的传统方法(即创建HttpResponseMessage或抛出 )HttpResponseException仍然可供您使用,但IHttpActionResult开发它是为了简化流程。
该IHttpActionResult接口有一种方法:
public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)
该NotFound方法只是创建一个NotFoundResult返回空响应的HttpStatusCode.NotFound。这本质上与 throw 的作用完全相同HttpResponseException(HttpStatusCode.NotFound),但语法更统一。
该IHttpActionResult界面还允许您轻松创建自定义ActionResult类以返回HttpStatusCode您想要的任何或任何内容类型。
| 归档时间: |
|
| 查看次数: |
3593 次 |
| 最近记录: |