WebAPI方法应如何返回错误响应?

时间:2020-03-16 07:54:25

标签: asp.net-web-api

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

错误CS0155被捕获或引发的类型必须源自 System.Exception

public IHttpActionResult GetAllData()
{
    using (sandminingEntities entities = new sandminingEntities())
    {
        try
        {
            return Ok( entities.GPSTrackers.OrderByDescending(x=>x.DeviceTimeStamp).ToList());
        }
        catch (Exception Ex)
        {
            throw Ex.Message;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

最简单的方法是,使用适当的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;

答案 1 :(得分:0)

您不需要EX.MESSAGE 试试吧:

   catch (Exception ex)
                {
                    throw ex ;
                }