Reputation: 695
I have an web api POST method that returns a location header in the http response message when I post a message object that is saved successfully. The Post method is as follows:
public class MessagesController : ApiController
{
public HttpResponseMessage Post(Message message)
{
HttpResponseMessage result = new HttpResponseMessage();
if (ModelState.IsValid)
{
// code to save message in database
...
result = Request.CreateResponse(HttpStatusCode.Created);
result.Headers.Location = new Uri(Request.RequestUri, "messages/" + message.Id.ToString());
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest, GetErrorMessages());
}
return result;
}
private IEnumerable<string> GetErrorMessages()
{
return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
}
}
In my angular service, I am using the $resource service to make the POST request as follows:
myApp.factory("messageRepository", ['$resource', function ($resource) {
return {
save: function(message) {
return $resource('/api/messages').save(message);
}
};
}]);
In my angular controller, I am calling the save method of my angular service and use the $promise.then() to check for success and error:
myApp.controller('MessageController', ['$scope', 'messageRepository', '$location', '$timeout',
function ($scope, messageRepository, $location, $timeout) {
$scope.errors = [];
$scope.save = function (message) {
$scope.sendingdata = true;
accountRepository.save(message).$promise.then(
// handle success
function (data) {
},
// handle error
function (response) {
$scope.errors = response.data;
});
};
}])
How do I access the response location header in the success handler function in the controller?
Upvotes: 0
Views: 1161
Reputation: 3820
You need to pass a success function to the save method that will have the headers as an argument. Try this:
myApp.factory("messageRepository", ['$resource', function ($resource) {
return {
save: function(message) {
return $resource('/api/messages').save(message, function(value, responseHeaders) {
return responseHeaders().Location;
});
}
};
}]);
Upvotes: 0