【问题标题】:How to return "response" back to angular code from async method in ASP.NET WEB API如何从 ASP.NET WEB API 中的异步方法将“响应”返回到角度代码
【发布时间】:2016-08-02 05:59:21
【问题描述】:

我正在从下面的角度代码发布到 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 函数,因为该方法是异步的,我不知道如何处理。

谢谢

【问题讨论】:

  • 客户端post数据为字符串:"data: JSON.stringify(test)",你的代码"JsonConvert.SerializeObject(payload)"没有效果!
  • 为什么在服务器代码中又调用了另一个api?可以在客户端代码中直接调用api!

标签: c# angularjs asp.net-web-api


【解决方案1】:

试试这个:

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

}

【讨论】:

  • 客户端post数据为字符串:“data: JSON.stringify(test)”,服务端代码“JsonConvert.SerializeObject(payload)”无效!
【解决方案2】:

通过使用 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;
        }

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-27
    • 2016-08-30
    • 2018-05-15
    • 2018-04-23
    • 1970-01-01
    • 2020-02-07
    • 2018-07-09
    • 2016-09-16
    相关资源
    最近更新 更多