C# 如何在 Web API 中抛出异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14607844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to throw exception in Web API?
提问by Alvin
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
错误?
采纳答案by Filip W
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"));
}
回答by Youssef Moussaoui
This should help you understand WebAPI error handling a bit better:
这应该可以帮助您更好地理解 WebAPI 错误处理:
http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
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. 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.
您的代码片段中的内容应该可以工作。如果测试为空且没有响应正文,服务器将向客户端发回 404 Not Found。如果您想要一个响应正文,您应该考虑使用 Request.CreateErrorResponse,如上面博客文章中所述,并将该响应传递给 HttpResponseException。