【问题标题】:Return error message from Web Api to $http从 Web Api 返回错误消息到 $http
【发布时间】:2017-03-09 10:46:35
【问题描述】:

我正在使用 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);
  }
}

角度调用:

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

【问题讨论】:

    标签: angularjs asp.net-web-api


    【解决方案1】:

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

    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);
      }
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 2018-07-09
      • 2021-11-27
      • 2019-02-24
      相关资源
      最近更新 更多