0

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

2
  • The client post data is a string: "data: JSON.stringify(test)", your code "JsonConvert.SerializeObject(payload)" have no effect! Commented Aug 2, 2016 at 6:47
  • Why again in the server code calls another api? You can call the api directly in the client code! Commented Aug 2, 2016 at 6:52

2 Answers 2

1

try this:

public async testModel 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();
            return test;      
        }
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

The client post data is a string: "data: JSON.stringify(test)", the server code "JsonConvert.SerializeObject(payload)" have no effect!
0

By using Task<TResult> this can be achievable as below:

public class CallRestAPIController:ApiController
{
    public async Task<string> 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);
                return test.Response = Desobj.ToString();
            }
             return string.Empty;
        }

    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.