gpt4 book ai didi

C# POST 请求到 webapi 使用控制台程序

转载 作者:太空宇宙 更新时间:2023-11-03 12:42:08 27 4
gpt4 key购买 nike

我有一个可以通过浏览器成功访问的 web api :-

https://127.0.0.1:8443/ncrApi

我正在尝试使用 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

最佳答案

您可能收到错误,因为最终地址是您的基本地址 + 邮寄地址,即:http://localhost:8443/nrcApi/nrcApi , 不存在

尝试将您的 client.BaseAddress 更改为:

client.BaseAddress = new Uri("https://localhost:8443/");

对于 SSL 连接错误,请尝试生成受信任的证书: Make https call using httpclient

关于C# POST 请求到 webapi 使用控制台程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38572752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com