从Web Api返回错误消息到$ http

时间:2017-03-09 10:46:35

标签: angularjs asp.net-web-api

我正在使用Angular 1.5和ASP.Net WebApi 2.我想在$ http.get请求失败时显示错误消息。不幸的是,错误回调只包含一般状态文本(例如内部服务器错误),但不包含我指定的消息。我该如何实现呢?

Web Api控制器:

public IHttpActionResult GetSomething()
{
  try
  {
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(GetContent(...));
    return ResponseMessage(result);
  }
  catch (Exception ex)
  {
    return InternalServerError(ex);
  }
}

Angular call:

$http.get('url')
.then(function (result) {
...            
}, function (error) {
  //$scope.errorMessage= ???
});

1 个答案:

答案 0 :(得分:0)

您可以创建自己的结果,其中包含您想要的任何内容:

public class ServerErrorResult : HttpActionErrorResult
{
    public Exception Exception {get; set;}

    public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = Content;
        if(Exception != null)
        {
            content += $"\r\nException Details:{Exception.Message}";
        }
        var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(content),
            RequestMessage = Request;
        };

        return Task.FromResult(response);
    }
}

然后在您的控制器中,您只需返回此新结果:

public IHttpActionResult GetSomething()
{
  try
  {
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(GetContent(...));
    return ResponseMessage(result);
  }
  catch (Exception ex)
  {
    return new ServerErrorResult 
        {
            Exception = ex
        };
  }
}

您还可以在控制器上创建一个扩展方法,以抽象出一些管道:

public static HttpActionErrorResult ServerError(this ApiController controller, Exception ex)
{
    return new ServerErrorResult 
        {
            Exception = ex
        };
}

然后从控制器中调用它:

public IHttpActionResult GetSomething()
{
  try
  {
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(GetContent(...));
    return ResponseMessage(result);
  }
  catch (Exception ex)
  {
      return ServerError(ex);
  }
}

希望有所帮助。