2014-01-16 52 views
2

我正在通过Badrinarayanan Lakshmiraghavan的“Practial ASP.NET Web API”中的教程工作。抛出HttpResponseException导致未处理的异常

我认为这是建议可以使用一些例外发送一个“404 - 未找到”类型的东西回浏览器。不过,我只是得到常规程序“崩溃”(错误消息弹出)。

我一定错过了什么。谁能告诉我它可能是什么? (这里有很多类似的问题,但我无法找到一个这种情况)。

我得到...用

"HttpResponseException was unhandled by user code" 

网址...

http://localhost:63694/api/employees/12344

代码...

public class EmployeesController : ApiController 
{ 
    private static IList<Employee> list = new List<Employee>() 
    { 
     new Employee() { 
     Id = 12347, FirstName = "Joseph", LastName = "Law"} 
    }; 


    // GET api/employees 
    public IEnumerable<Employee> Get() 
    { 
     return list; 
    } 

    // GET api/employees/12345 
    public Employee Get(int id) 
    { 
     var employee = list.FirstOrDefault(e => e.Id == id); 

     if (employee == null) 
     { 
      throw new HttpResponseException(HttpStatusCode.NotFound); 
     } 

     return employee; 
    } 
} 
+0

你可以显示你声明控制器类的整个行吗? –

+0

@G。斯托涅夫,你什么意思。所有控制器类都在上面。只是名称空间,使用和雇员定义丢失。你需要哪些? – spiderplant0

+0

我肯定错过了:-)在这种情况下 - 当它到达管线末端时,异常应该转换为HttpMessage。 –

回答

2

的WebAPI应该处理异常和返回状态代码包含在其中。有可能你在ApiController衍生的控制器中运行这个,但是从Controller派生出一个。

你最好用Employee类型的内容返回HttpResponseMessage。在这种情况下,你有更好的控制研究过的状态代码,就像这样:

var response = Request.CreateResponse(HttpStatusCode.Notfound); 
return response 

// GET api/employees/12345 
public HttpResponseMessage Get(int id) 
{ 
    HttpResponseMessage response = null; 
    var employee = list.FirstOrDefault(e => e.Id == id); 

    if (employee == null) 
    { 
     response = new HttpResponseMessage(HttpStatusCode.NotFound); 
    } 
    else 
    { 
     response = Request.CreateResponse(HttpStatusCode.OK, employee); 
    } 

    return response; 
} 
+0

感谢,这似乎是一个更合乎逻辑的方法 - 返回somethign,而不是引发异常。 – spiderplant0

+1

为了一致性,我相信条件if(employee == null)应该创建如下响应:response = Request.CreateErrorResponse(HttpStatusCode.NotFound,“Employee not found”); – dotnetguy

0

其实,你可以做其他2位用户发布什么,而是你正在做的方式是正确的。

的Web API异常处理:http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

但是,如果你在调试模式下在Visual Studio中运行,VS会警告你未处理的异常和这样。但是,如果您不以调试模式运行,或者如果您部署到IIS,则该行为将正常工作,并会呈现404 Not Found错误页面。

Visual Studio只是试图检测并阻止所有未处理的异常,从而阻碍了您的工作。

+0

谢谢,我试着将它设置为'释放'模式,但仍然出现错误。 – spiderplant0

+0

您是否启动调试器(F5 /播放按钮)或者只是编译和访问您的网站?你有没有尝试过部署到IIS? – Karhgath

相关问题