简体   繁体   English

如何在 Web API 中抛出异常?

[英]How to throw exception in Web API?

How can I throw a exception to in ASP.net Web Api?如何在 ASP.net Web Api 中抛出异常?

Below is my code:下面是我的代码:

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

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

    return test;
}

I don't think I am doing the right thing, How do my client know it is a HTTP 404 error?我认为我做的不对,我的客户怎么知道这是HTTP 404错误?

It's absolutely fine.绝对没问题。

Alternatively, if you wish to provide more info (to allow, as you say, the client to distinguish from regular 404):或者,如果您希望提供更多信息(如您所说,允许客户端与常规 404 区分开来):

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

This blogpost should help you understand WebAPI error handling a bit better. 这篇博文应该可以帮助您更好地理解 WebAPI 错误处理。

What you have in your code snippet should work.您的代码片段中的内容应该可以工作。 The server will send back a 404 Not Found to the client if test is null with no response body.如果测试为空且没有响应正文,服务器将向客户端发回 404 Not Found。 If you want a response body, you should consider using Request.CreateErrorResponse as explained in the blog post above and passing that response to the HttpResponseException .如果您想要一个响应正文,您应该考虑using Request.CreateErrorResponse如上面的博客文章中所述,并将该响应传递给HttpResponseException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM