如何在Web API中抛出异常?

Alv*_*vin 36 .net c# exception asp.net-web-api

如何在ASP.net Web Api中抛出异常?

以下是我的代码:

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

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

    return test;
}
Run Code Online (Sandbox Code Playgroud)

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

Fil*_*p W 66

这绝对没问题.

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

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

  • 但是当我将它托管到 Web 服务器时,我总是收到 HTTP 500 错误。 (2认同)

You*_*oui 5

这应该可以帮助您更好地理解WebAPI错误处理:

http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

您的代码段中的内容应该有效.如果测试为空且没有响应正文,则服务器将向客户端发回404 Not Found.如果您需要响应主体,则应考虑使用Request.CreateErrorResponse,如上面的博客文章中所述,并将该响应传递给HttpResponseException.