簡體   English   中英

如何從ASP.NET WEB API中的異步方法將“響應”返回到角度代碼

[英]How to return “response” back to angular code from async method in ASP.NET WEB API

我正在從下面的角度代碼發布到webapi異步方法:

    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.
            });
        };

});

這是控制器:

 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();

            }
        }

    }

}

我怎樣才能返回test.Response回角successCallback功能,因為該方法是異步,我不知道如何處理這個問題。

謝謝

嘗試這個:

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

}

通過使用Task<TResult >,可以實現以下目的:

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

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM