2017-08-01 72 views
0

我想添加一個新的Stop到我的數據庫。但我在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; 
} 

我已閱讀,這可能是因爲數據格式不正確,有人知道什麼是正確的格式,我的網頁返回錯誤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#代碼。現在更明顯的是什麼可能導致這個問題? –