如何从asp.net Web API 使用webApi 将结果存储在数据库中? [英] How to consume a webApi from asp.net Web API to store result in database?

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

问题描述

我想知道如何使用来自另一个 ASP.Net Web API 的 WEBAPI 将响应存储在数据库中.我知道如何从 javascript、控制台应用程序等客户端使用 WEBAPI.

I'm wondering 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 来做到这一点?

Is it possible to do this with an Asp.Net Web API?

推荐答案

在本教程中解释了如何使用 C# 使用 web api,在此示例中使用了控制台应用程序,但您可以当然也使用另一个web 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.

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

确保您的请求使用 Accept 标头以 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
}

请注意,我在示例中使用了 .Result.您应该考虑在此处使用 async await 模式.

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天全站免登陆