抛出HttpResponseException会导致未处理的异常

时间:2014-01-16 19:28:20

标签: c# asp.net-web-api

我正在通过Badrinarayanan Lakshmiraghavan的“Practial ASP.NET Web API”中的教程。

我认为这表明可以使用一些例外将“404 - Not Found”类型的东西发送回浏览器。但是我只是让常规程序“崩溃”(弹出错误信息)。

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

我明白了......

"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;
    }
} 

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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通过尝试检测并阻止所有未处理的异常来阻碍您。