HttpResponseException

Hop*_*ope 5 asp.net-mvc-4 asp.net-web-api

我在处理 MVC 4 webAPI 中的错误时遇到了一个大问题。在这里,我想验证传入的请求并发回 BadRequest 响应。

为此,我正在使用代码

public Product GetProduct(int id)
{
    Product item = repository.Get(id);
   if (item == null)
   {
     throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
   }
   return item;
}
Run Code Online (Sandbox Code Playgroud)

但是在空 id 的情况下,VS2010 会产生另一个错误,如

“处理 HTTP 请求导致异常。有关详细信息,请参阅此异常的 'Response' 属性返回的 HTTP 响应”。

我该如何解决这个问题

提前致谢....

Dar*_*rov 2

使用路由约束来禁用nullids: @"\d+"。这样,如果您不在 url 中传递数字 id,控制器操作甚至不会解析,路由引擎将直接返回 404。