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

标签 c# asp.net-web-api

我正在学习 Badrinarayanan Lakshmiraghavan 撰写的“实用 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;
    }
} 

最佳答案

WebApi 应该处理异常并返回其中包含的状态代码。您可能不是在 ApiController 派生的 Controller 中运行它,而是在 Controller 派生的 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;
}

关于c# - 抛出 HttpResponseException 会导致未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21171059/

相关文章:

c# - JavaScript 生成的网页问题

c# - 禁用 ASP :dropdownlist based on the selection of another ASP:Dropdownlist. 值

c# - ASP.NET - 复合控件 - 在 CreateChildControls 抑制 Button Click 事件后添加动态控件

rest - 如何通过http客户端强制调用restful服务?

javascript - 从 Dropzone 获取上传的文件

c# - 使用 C# 创建 ics 文件并发送带有附件的电子邮件

c# - 防止 WinForms PictureBox 动画 GIF 在处理过程中暂停?

jquery - 具有大型数据集 (json) 的 ASP.NET WebAPI 和 jQuery

asp.net-mvc-4 - 使用不带 global.asax 的结构图注入(inject) NServiceBus

c# - 如何读取包含 Datetime 类型的 BaseHttpActionResult 的响应