简体   繁体   中英

AngularJS + ASP.NET $http.post returning 401

I am trying to add a new Stop to my database. But I get a 401 error in asp.net.

.js file:

(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 file (input form):

<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# Post code:

 [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;
}

I have read, that this is probably caused because the data is not in the right format, does anyone know what would be the right format, my webpage returns error 400, but deeper in my C# I can see that function var json = await client.GetStringAsync(url); is returning an error 401 (Unotharized). I guess I should also add username somewhere, but I don't know where.

You're getting a 400 because the request you sent isn't what the server is expecting. Find out the object the server is expecting on that endpoint. Then form your request body to match that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM