我有一个可以通过浏览器成功访问的web api: -
我正在尝试使用VS2015在C#中创建一个简单的控制台程序来发送数据并使用http POST接收响应。
以下是我到目前为止: -
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace WebSample
{
class ApiSendData
{
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())
{
// 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/ncrApi");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var datatobeSent = new ApiSendData()
{
ApiFunction ="NcrSecureData",
DppName ="CSampleCustomer",
DppVersion ="Latest",
ClearData ="1234567890"
};
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 //
}
}
}
}
}
但是我在HttpResonseMessage响应语句中收到错误.... {"发送请求时出错。"} {"请求已中止:无法创建SSL / TLS安全通道。"}
我怀疑是因为我没有正确理解client.BaseAddress和HttpResponseMessage响应语句。
以下是我一直关注的事项: - http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
答案 0 :(得分:1)
您可能收到错误,因为最终地址是您的baseAddress +帖子地址,即:http://localhost:8443/nrcApi/nrcApi,它不存在
尝试将您的client.BaseAddress更改为:
client.BaseAddress = new Uri("https://localhost:8443/");
对于SSL连接错误,请尝试生成可信证书: Make https call using httpclient
答案 1 :(得分:0)
您的代码看起来不错。但是,问题似乎出在您拨打的电话上。基本上在以下调用中,第一个参数是要在 URI 之后调用的方法/函数。
<块引用>HttpResponseMessage response = await client.PostAsJsonAsync("ncrApi", 发送数据);
在这种情况下,ncrApi 是您的方法。在基本 URL 中调用它会导致它被添加到最终调用中,从而为不存在的端点提供地址。