如何抛出异常的Web API? [英] How to throw exception in Web API?

查看:193
本文介绍了如何抛出异常的Web API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以抛出一个异常在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");
    }

这篇关于如何抛出异常的Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆