【问题标题】:How to throw exception in Web API?如何在 Web API 中抛出异常?
【发布时间】:2013-01-30 15:40:13
【问题描述】:

如何在 ASP.net Web Api 中引发异常?

下面是我的代码:

public Test GetTestId(string id)
{
    Test test = _test.GetTest(id);

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

    return test;
}

我认为我做的不对,我的客户怎么知道这是 HTTP 404 错误?

【问题讨论】:

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


    【解决方案1】:

    没问题。

    或者,如果您希望提供更多信息(如您所说,允许客户端与常规 404 区分开来):

        if (test == null)
        {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, 
    "this item does not exist"));
        }
    

    【讨论】:

    • 但是当我将它托管到 Web 服务器时,我总是收到 HTTP 500 错误。
    • @Alvin 你是从 ApiController 继承你的控制器吗?还要检查这个 GetTestId 方法是否不是从构造函数中调用的,只是为了确定。如果一切都失败了,尝试以下抛出错误: throw new HttpException((int)HttpStatusCode.NotFound,"this item does not exist");
    【解决方案2】:

    This blogpost 应该可以帮助您更好地理解 WebAPI 错误处理。

    您的代码 sn-p 中的内容应该可以工作。如果测试为空且没有响应正文,服务器将向客户端发送 404 Not Found。如果您想要一个响应正文,您应该考虑using Request.CreateErrorResponse,如上面的博客文章中所述,并将该响应传递给HttpResponseException

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 2013-01-02
      • 2013-11-08
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多