如何使用来自asp.net的Web API中的WebAPI存储导致数据库? [英] How to consume a webApi from asp.net Web API to store result in database?

查看:203
本文介绍了如何使用来自asp.net的Web API中的WebAPI存储导致数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从另一个ASP.Net网页API消耗的WebAPI存储在数据库中的响应。
我知道如何从如JavaScript,控制台应用程序等客户消耗的WebAPI。

How to consume a WEBAPI from another ASP.Net Web API to store the response in a database. I know how to consume a WEBAPI from clients like javascript,console application etc.

但要求是由我的WebAPI和放大器拉第三方API数据;因此使用我的WebAPI的结果存储在数据库中我的客户要求我的数据。

But the requirement is to pull the data from third party API by my WEBAPI & store the result in a database so that using my WEBAPI my clients request me for data.

如何使用Asp.Net的Web API是可能的?

How can it be possible using Asp.Net Web API ?

推荐答案

在本教程介绍了如何消耗的网页API 用C#,在这个例子中一个控制台应用程序被使用,但你可以还用另一个网络API 消耗,当然。

In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

<一个href=\"http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client\">http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

您应该看一看在的HttpClient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/yourwebapi");

请确保您的要求使用接受这样的标题为JSON响应问:

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

现在来从教程不同的部分,请确保您有相同的对象与其他 WEB API ,如果没有,那么你必须将对象映射自己的对象。 ASP.NET 将转换成 JSON 您收到你希望它是对象。

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
    var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
    foreach (var x in yourcustomobjects)
    {
        //Call your store method and pass in your own object
        SaveCustomObjectToDB(x);
    }
}
else
{
    //Something has gone wrong, handle it here
}

请注意,我用。结果的例子中。你应该考虑在这里使用异步 等待模式。

please note that I use .Result for the case of the example. You should consider using the async await pattern here.

这篇关于如何使用来自asp.net的Web API中的WebAPI存储导致数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆