Asp.net web api WebAPI方法应该如何返回错误响应?
我想在Web API响应中看到错误消息。异常消息应如何显示在响应中 错误CS0155捕获或抛出的类型必须派生自 系统异常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) {
最简单的方法是使用适当的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 ;
}