【问题标题】:Asp.net WebApi method instead of AngularJs ServiceAsp.net WebApi 方法而不是 AngularJs 服务
【发布时间】:2017-02-14 03:36:43
【问题描述】:

我已经编写了如下所示的 Angularjs 服务。它从 3rd 方服务检索数据。它工作正常。

现在我需要为此编写一个 WebApi 方法。这样做的原因是,我们可以从各种类型的应用程序中使用该服务。即桌面、网络和移动设备。我怎样才能实现这样的服务?

AngulaJS 服务:

(function () {
    appModule.service('getPropertyDetailsByUsingApiService', ['$http', function ($http) {
        this.propertyDetails = function (token, number, street, county, zip) {
            var endpointUrl = 'http://myaddress.com/api/AddressMatcher?Token=';
            var url = endpointUrl + token + '&Number=' + number + '&Street=' + street + '&County=' + county + '&Zip=' + zip;

            return $http.get(url).then(function (data) {
                var result = data;
                if (result.data[0].Status == 'OK') {
                    return $http.get(endpointUrl + token + '&Apn=' + result.data[0].Result[0].APN + '&County=' + county)
                        .then(function (finalData) {
                            return finalData;
                        });
                } else {
                    return null;
                }
            });
        };
    }
    ]);
})();

WebApi 方法:

    [HttpGet]
    public async Task<MyModelDto> GetPropertyDetailsByUsingApiService()
    {
        //I would like to have a help here to implement it

        return result;
    }

【问题讨论】:

  • 您期望输出什么?你能详细说明一下吗?
  • 我可以管理输出。我只需要知道如何在 Web API 中调用上述 3rd 方服务。 @Pavvy
  • 请检查我的回答。

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


【解决方案1】:

我猜你正在寻找HttpClient.GetAsync

例如,

var response = await client.GetAsync("http://...");
if (response.IsSuccessStatusCode) {
    ...
}

【讨论】:

    【解决方案2】:

    使用这个,

    using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiDetails.BaseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                
                HttpResponseMessage response = client.PostAsJsonAsync(apiDetails.RequestUrl, obj).Result;                
            }
    

    【讨论】:

      猜你喜欢
      • 2016-04-17
      • 2016-12-03
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多