正在读取angular js promise中的NegotiatedContentResult对象(从WebAPI发送)

Reading from NegotiatedContentResult object (sent from WebAPI) in angular js promise

本文关键字:对象 WebAPI 发送 NegotiatedContentResult 中的 读取 angular js promise      更新时间:2024-03-30

下面显示的是我的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)"时,一些人的角度代码无法读取此内容,并抛出异常,并显示警告消息"Oops something error[object object]",因此它似乎正在获取数据,但由于某种原因,它仍然抛出异常。有人来帮忙吗?

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

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

这是由于在您的http请求中添加了CCD_ 1。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状态文本。