如何抛出异常的Web API?抛出、异常、API、Web

2023-09-04 02:35:48 作者:尛尛糖°

我如何可以抛出一个异常在ASP.net中的Web API?

How can I throw a exception to in ASP.net Web Api?

下面是我的code:

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

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

    return test;
}

我不认为我做了正确的事,怎么办我的客户知道这是一个 HTTP 404 错误?

推荐答案

这绝对是很好。

另外,如果你想提供更多的信息(允许,就像你说的,客户端从常规的404区别):

Alternatively, if you wish to provide more info (to allow, as you say, the client to distinguish from regular 404):

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