Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net web api WebAPI方法应该如何返回错误响应?_Asp.net Web Api - Fatal编程技术网

Asp.net web api WebAPI方法应该如何返回错误响应?

Asp.net web api WebAPI方法应该如何返回错误响应?,asp.net-web-api,Asp.net Web Api,我想在Web API响应中看到错误消息。异常消息应如何显示在响应中 错误CS0155捕获或抛出的类型必须派生自 系统异常 最简单的方法是使用适当的Http状态代码从操作方法中抛出“System.Web.Http.HttpResponseException” try { ... } catch (Exception exception) { var message = new HttpResponseMessage(HttpStatusCode.BadRequest) {

我想在Web API响应中看到错误消息。异常消息应如何显示在响应中

错误CS0155捕获或抛出的类型必须派生自 系统异常


最简单的方法是使用适当的Http状态代码从操作方法中抛出“System.Web.Http.HttpResponseException”

try
{
    ...
}
catch (Exception exception)
{
    var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
        Content = new StringContent(exception.Message),
        ReasonPhrase = "Bad Request"
    };

    throw new HttpResponseException(message);
}

return result;
你不需要前消息 试试看:


获取错误-无法将类型“string”隐式转换为“System.Net.Http.HttpContent”修改了答案。Content属性现在是StringContent的实例。
try
{
    ...
}
catch (Exception exception)
{
    var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
        Content = new StringContent(exception.Message),
        ReasonPhrase = "Bad Request"
    };

    throw new HttpResponseException(message);
}

return result;
   catch (Exception ex)
                {
                    throw ex ;
                }