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.
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.
Is it possible to do this with an Asp.Net Web API?
Let's assume, we have a requirement to send a file based on the file type provided to the service request. For example, when we send the file type as PDF, service will return PDF file if we send Doc, service will return Word document. (I have taken this sample to cover all types of files).
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
You should have a look at the HttpClient
HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost/yourwebapi");
Make sure your requests ask for the response in JSON using the Accept header like this:
client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/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.
For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:
HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects"); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); var product = JsonConvert.DeserializeObject<Product>(data); }
This way my content is parsed into a JSON string and then I convert it to my object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With