【问题标题】:Reading from NegotiatedContentResult object (sent from WebAPI) in angular js promise从 Angular js Promise 中读取 NegotiatedContentResult 对象(从 WebAPI 发送)
【发布时间】:2017-03-10 13:49:12
【问题描述】:

下面显示的是我的 WebAPI 方法,它返回有关几本书的信息列表。

   [System.Web.Http.Authorize]
    public async Task<IHttpActionResult> Get(Guid id)
    {
        try
        {
            var result = await _assetAssetRepository.View(id);
            if (result == null)
            {
                return NotFound();
            }
             return Content(HttpStatusCode.Found, result);
        }
        catch (Exception ex)
        {
            return Content(HttpStatusCode.InternalServerError,
                "Exception Occurred" + ex.Message + " " + ex.StackTrace);
        }

    }

使用此数据的 Angular js 代码

    var getAssetDetails = function (assetId) {
    var deferred = $q.defer();
    $http.get("/api/Asset/" + assetId, { headers: { 'Authorization': 'Bearer ' + $cookies.get('accessToken') } })
         .then(function (response) {
             deferred.resolve(response);
         }).catch(function (response) {
             alert("Oops something wrong: " + response.data);
             deferred.reject(response);
         }).finally(function () {

         });
    return deferred.promise;
};

我正在苦苦挣扎的一点是,如果您在 webapi 中替换这行代码
“return Content(HttpStatusCode.OK,result)”和“return Ok(result)”我可以毫无问题地在 UI 中看到数据。但是,当我使用
“return Content(HttpStatusCode.OK,result)”时,某些角度代码无法读取此内容并抛出异常并显示警告消息“糟糕,错误 [object Object]”,所以看起来像它获取数据但由于某种原因它仍然抛出异常。有人要帮忙吗?

【问题讨论】:

  • 在您的catch 回调中,您会收到一个异常作为参数,而不是http 响应。请分析此异常,以便我们为您提供更好的帮助。
  • 试试response.responseTextresponse.responseJSON

标签: javascript c# angularjs http asp.net-web-api


【解决方案1】:

嗯,最好从 catch 块给出的细节开始。但是许多错误之一可能是(我第一次遇到的):

JSON 中位置 0 处的意外标记 R

这是由于在您的 http 请求中添加了responseType: 'JSON'。 Angular 将响应视为 JSON,在这种情况下它不是。所以我们需要删除它。

这是我的做法(端到端)。从我的 API:

 return Content(HttpStatusCode.<statuscode>, "ResponseContent: " + "my_custom_error");

第二种情况:

//If I'm getting output from another API/Layer then I pass it's output like this
var output = response.Content.ReadAsStringAsync().Result;
return Content(response.StatusCode, "ResponseContent: " + output);

在 Angular 代码中,我是这样读的:

$http({ method: methodType, url: endpoint })
     .then(function (response) {
          response.status; //gets you the HttpStatusCode to play with
          response.data; //gets you the ReponseContent section
     }, function (response) {
          response.status; //gets you the HttpStatusCode
          response.data; //gets you the ReponseContent section
     });

来自https://docs.angularjs.org/api/ng/service/$http

响应对象具有以下属性:

data – {string|Object} – 使用 变换函数。

status – {number} – 响应的 HTTP 状态码。

headers – {function([headerName])} – Header getter 函数。

config – {Object} – 用于配置的配置对象 生成请求。

statusText – {string} – 响应的 HTTP 状态文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多