通过控制台程序的C#webapi POST
本文关键字:C#webapi POST 程序 控制台 | 更新日期: 2023-09-27 17:58:32
我有一个可以通过浏览器成功访问的web api:-
https://127.0.0.1:8443/ncrApi
我正在尝试使用VS2015在C#中创建一个简单的控制台程序,以便使用httpPOST发送数据和接收响应。
以下是我目前所拥有的:-
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace WebSample
{
class ApiSendData
{
public string UserID { get; set;} // username
public string Password { get; set;} // password for the webapi
public string ApiFunction { get; set; }
public string DppName { get; set; }
public string ClearData { get; set; }
public string DppVersion { get; set; }
}
class Program
{
static void Main(string[] args)
{
// The Main function calls an async method named RunAsync
// and then blocks until RunAsyncc completes.
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
//specify to use TLS 1.2 as default connection
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
// This code sets the base URI for HTTP requests,
// and sets the Accept header to "application/json",
// which tells the server to send data in JSON format.
client.BaseAddress = new Uri("https://localhost:8443/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var datatobeSent = new ApiSendData()
{
UserID = "xxxx",
Password = "yyyy",
ApiFunction ="NcrSecureData",
DppName ="CSampleCustomer",
DppVersion ="Latest",
ClearData ="1234567890",
ResultType = "JSON"
};
HttpResponseMessage response = await client.PostAsJsonAsync("ncrApi", datatobeSent);
if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri ncrUrl = response.Headers.Location;
// do whatever you need to do here with the returned data //
}
}
}
}
}
在我的响应变量中,我得到了200 OK http 1.1消息,内容类型=application/json,内容长度=174……但没有收到实际数据。。。
变量ncrUrl也是null。。。。
我想知道我的控制台程序中是否需要额外的语句来接收数据?
以下是我一直关注的内容:-http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
阅读注释后,您的api似乎被配置为返回一个文件,而不是JSON或XML等字符串内容。您可以使用HttpContent.ReadAsStreamAsync方法读取响应流并将其保存到文件中。
HttpResponseMessage response = await client.PostAsJsonAsync("ncrApi", datatobeSent);
using (Stream output = File.OpenWrite("filename.txt")) // change
{
using (Stream input = await response.Content.ReadAsStreamAsync())
{
input.CopyTo(output);
}
}