2016-04-10 12 views
0

以下に、いくつかの書籍に関する情報のリストを返すWebAPIメソッドを示します。角度のjs約束でNegotiatedContentResultオブジェクト(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); 
     } 

    } 

このデータを消費する角度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
にと「リターンコンテンツ(HttpStatusCode.OK、結果を)」のコード行を置き換える場合、私は苦労していますビットであります"return Ok(result)" UIのデータは問題なく見ることができます。しかし、私が
"返信コンテンツ(HttpStatusCode.OK、result)"を使用すると、一部の角度コードがこれを読み取ることができず、例外がスローされ、 "間違った[オブジェクトオブジェクト]"というアラートメッセージが表示されます何らかの理由でデータがまだスローされている例外です。誰でも助けてくれる?

+0

あなたの 'catch'コールバックの中で、http応答ではなくパラメータとして例外を受け取ります。この例外を分析して、より良くお手伝いできるようにしてください。 –

+0

'response.responseText'または' response.responseJSON'を試してください – Sam

答えて

0

さて、キャッチブロックの詳細から始めてください。しかし、多くのエラーのいずれかが(私が最初に持っていた)ことができます:JSONで

予期しないトークンRによるあなたのHTTPリクエストに追加responseType: 'JSON'にすることである位置0

で。 AngularはレスポンスをJSONとして受け取りますが、ここではそうではありません。だから我々はこれを削除する必要があります。

これは私がそれを行う方法です(エンドツーエンド)。

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

第二ケース::私のAPIから

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

と角のコードで、私はこのようにそれを読む:レスポンスオブジェクトはあり

$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} - 変換関数で変換された応答本体です。

ステータス - {number} - 応答のHTTPステータスコード。

ヘッダー - {function([headerName])} - ヘッダーゲッター機能。

config - {オブジェクト} - に要求を生成するために使用された構成オブジェクト。

statusText - {string} - レスポンスのHTTPステータステキスト。

関連する問題