2017-08-01 16 views
0

私のデータベースに新しい停止を追加しようとしています。しかし、私はasp.netで401エラーが発生します。

.jsファイル:

(function() { 
    "use strict"; 
    angular.module("app-trips") 
     .controller("tripEditorController", tripEditorController); 
    function tripEditorController($routeParams, $http) { 
     var vm = this; 
     vm.tripName = $routeParams.tripName; 
     vm.stops = []; 
     vm.newStop = {}; 

     vm.addStop = function() { 
      alert(vm.newStop.name); 
      $http.post("/api/trips/" + vm.tripName + "/stops", vm.newStop) 
       .then(function (response) { 
        vm.stops.push(vm.newStop); 
       }; 
     } 
} 

の.htmlファイル(入力フォーム):

<form novalidate name="newStopForm" ng-submit="vm.addStop()"> 
    <div class="form-group"> 
     <label for="">Date</label> 
     <input class="form-control" id="arrival" name="arrival" ng-model="vm.newStop.arrival" required /> 
    </div> 
    <div class="form-group"> 
     <label>Location</label> 
     <input class="form-control" id="name" name="name" ng-model="vm.newStop.name" required ng-minlength="3" /> 
    </div> 
    <div> 
     <input type="submit" value="Add" class="btn btn-success" ng-disabled="newStopForm.$invalid" /> 
    </div> 
</form> 

C#郵便番号:

[HttpPost("/api/trips/{tripName}/stops")] 
     public async Task<IActionResult> Post(string tripName, [FromBody]StopViewModel vm) 
     { 
      try 
      { 
       if (ModelState.IsValid) 
       { 
        var newStop = Mapper.Map<Stop>(vm); 
        var result =await _coordsService.GetCoordsAsync(newStop.Name); 
        if (!result.Succes) 
        { 
         _logger.LogError(result.Message); 
        } 
        else 
        { 
         newStop.Latitude = result.Latitude; 
         newStop.Longitude = result.Longitude; 
        } 
        _repository.AddStop(tripName, newStop, User.Identity.Name); 
        if (await _repository.SaveChangesAsync()) 
        { 
         return Created($"/api/trips/{tripName}/stops/{newStop.Name}", 
             Mapper.Map<StopViewModel>(newStop)); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       _logger.LogError("Failed to save new Stop: {0}", ex); 
      } 
      return BadRequest("Failed to save new stop"); 
     } 

GeoCoordsService.cs:

public async Task<GeoCoordsResult> GetCoordsAsync(string name) 
{ 
    var result = new GeoCoordsResult() 
    { 
     Succes = false, 
     Message = "Failed to get coordinates" 
    }; 
    var apiKey = _config["Keys:BingKey"]; 
    var encodedName = WebUtility.UrlEncode(name); 
    var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={apiKey}"; 

    var client = new HttpClient(); 
    var json = await client.GetStringAsync(url); 

    var results = JObject.Parse(json); 
    var resources = results["resourceSets"][0]["resources"]; 
    if (!resources.HasValues) 
    { 
     result.Message = $"Could not find '{name}' as a location"; 
    } 
    else 
    { 
     var confidence = (string)resources[0]["confidence"]; 
     if (confidence != "High") 
     { 
      result.Message = $"Could not find a confident match for '{name}' as a location"; 
     } 
     else 
     { 
      var coords = resources[0]["geocodePoints"][0]["coordinates"]; 
      result.Latitude = (double)coords[0]; 
      result.Longitude = (double)coords[1]; 
      result.Succes = true; 
      result.Message = "Success"; 
     } 
    } 
    return result; 
} 

データが適切なフォーマットでないために誰かが正しいフォーマットであるとわかっていますが、私のWebページはエラー400を返しますが、C#ではその機能を見ることができるので、これが原因であると私は読んでいます。var json = await client.GetStringAsync(url);エラー401(Unotharized)。私はどこかでユーザー名を追加するべきだと思いますが、私はどこにいるのかわかりません。

+0

そのエンドポイントのasp.netコードを送信すると便利です。 – Anthony

答えて

0

送信したリクエストがサーバーが期待しているものではないため、400が表示されます。サーバーがそのエンドポイントで予期しているオブジェクトを見つけます。その後、そのオブジェクトに一致するリクエスト本体を作成します。

+0

これはルーキーの質問かもしれませんが、サーバーが何を期待しているのかはどこで確認できますか?私はVisual StudioのIIS Expressをサーバーとして使用しています。 –

+0

エンドポイント「/ api/trips/tripname/stops」にPOST要求をしています。このasp.net-mvcというタグを付けているので、おそらくC#というエンドポイントを定義するコードがあります。サーバーは、そのルートのメソッドのパラメータとして、オブジェクトが予期しているものを見ることができます。 – Anthony

+0

私はC#コードも追加しました。何が問題を引き起こす可能性があるのか​​がはっきりしていますか? –

関連する問題