I am doing post to webapi async method from below angular code:
var app = angular.module('APItest', []);
app.controller('TestAPI', function ($scope, $http) {
debugger;
$scope.test = function () {
var test = $scope.testModel.CommandText;
$http({
method: 'POST',
url: '/api/CallRestAPI',
data: JSON.stringify(test),
contentType: 'application/json',
dataType: 'json'
}).then(function successCallback(response) {
$scope.response = response;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
this is the controller:
public class CallRestAPIController:ApiController
{
public async void PostToAPI([FromBody]string value)
{
var payload = value;
// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
// Do the actual request and await the response
var httpResponse = await httpClient.PostAsync("https://testapi.com/prod/testapi", httpContent);
// If the response contains content we want to read it!
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync();
// From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
testModel test = new testModel();
object Desobj = JsonConvert.DeserializeObject(responseContent);
test.Response = Desobj.ToString();
}
}
}
}
How can I return the test.Response back to the angular successCallback function, since the method is async and I dont know how to handle this.
Thanks