如何从asp.net Web API中使用webApi将结果存储在json文件中
本文关键字:webApi 结果 存储 文件 json asp net API Web | 更新日期: 2023-09-27 18:11:17
如何使用c#消费RestApi并将响应的内容存储在json文件中?即当我运行程序时,它应该调用API,并自动将json内容存储在json文件中。用Asp.Net怎么可能呢?
你应该使用HTTP POST
using System.Net.Https; // Add this library
using (var client = new HttpClient())
{
var values = "DataToSend";
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://sit.com/sample.aspx", content);
var responseString = await response.Content.ReadAsStringAsync(); //JSON
}
您可以使用httpclient(Microsoft.AspNet.WebApi.Client)调用任何rest api
下面的方法返回一个json字符串async,您可以稍后保存
static async Taskstring> GetContentAsync(string path)
{
using (var httpClient = new HttpClient())
return await httpClient.GetStringAsync(address);
}
同步获取json内容
using (var client = new HttpClient())
{
var response = client.GetAsync("http://example.com").Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseString);//you can save the responseString here
}
}
或使用RestSharp等开源库
var client = new RestClient("http://example.com");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
更多的例子可以找到https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client或使用restsharp