我想从控制器调用WebAPI。我也想从控制器传递多个json参数。那么,如何使用api绑定数据?
var jsonData = "{\"jsonrpc\":2.0," +
"\"method\":eth_blockNumber," +
"\"params\":[]," +
"\"id\":83}";
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(string.Format("https://mainnet.infura.io/qhggowRXK7HIgXB0NEyw",jsonData));
webreq.Method = "POST";
webreq.ContentType = "application/json";
using (var streamWriter = new StreamWriter(webreq.GetRequestStream()))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
//var resToWrite = serializer.Deserialize<Dictionary<string, object>>(jsonData);
//streamWriter.Write(jsonData);
streamWriter.Flush();
streamWriter.Close();
}
WebResponse response = webreq.GetResponse();
var streamReader = new StreamReader(response.GetResponseStream());
var result = streamReader.ReadToEnd();
答案 0 :(得分:1)
您可以使用HttpClient:
private static readonly HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2" }
};
*var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://mainnet.infura.io/qhggowRXK7HIgXB0NEyw", content);
var responseString = await response.Content.ReadAsStringAsync();
或者,如果您不使用NET 4.5或更高版本,则使用WebClient:
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
答案 1 :(得分:0)
您可以按如下所示简单地调用API:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://mainnet.infura.io/qhggowRXK7HIgXB0NEyw");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var requestBody = new
{
jsonrpc = "2.0",
method = "eth_blockNumber",
@params = new int[]{},
id = 83,
};
HttpResponseMessage apiResponse = await client.PostAsJsonAsync(client.BaseAddress, requestBody);
if (apiResponse.IsSuccessStatusCode)
{
var documentResponse = await apiResponse.Content.ReadAsStringAsync();
dynamic response = JsonConvert.DeserializeObject(documentResponse);
}
}
需要添加Http.Formatting.Extension的nuget包:
Install-Package System.Net.Http.Formatting.Extension
侧面说明:您将在动态变量中获得响应,此外,您还可以在模型中反序列化响应,而该响应未包括在内。