有以下代码与目标框架.net核心2.2与目标框架4.5一起使用是有问题的。
public async Task<string> GetConversationIdAsync()
{
try
{
var client = new HttpClient();
var content = new StringContent(" ", Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "XXXXXXXXXXXX");
var response = await client.PostAsync(
$"https://directline.botframework.com/v3/directline/conversations", content);///Error here
var result = await response.Content.ReadAsStringAsync();
return result;
}
catch (Exception ex)
{
throw;
}
}
出现此错误:位于System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务),位于OlyBot.Api的System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()处.BLL.Handoff.d__1.MoveNext()
这是什么问题
我也试过用
System.Net.WebRequest webRequest = System.Net.WebRequest.Create("https://directline.botframework.com/v3/directline/conversations");
webRequest.Method = "POST";
webRequest.Headers.Add("Authorization", "Bearer XXXXXXXXXXXXXX");
webRequest.Headers.Add("Content-Type", "application/json");
System.Net.WebResponse resp = webRequest.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd().Trim();
但这也行不通。
您不能将Content-Type设置为自定义标头,请执行以下操作:
webRequest.ContentType = "application/json";
此外,您需要将Content-Length包含在POST请求中:
string content = " ";
webRequest.ContentLength = content.Length;
之后你需要写数据:
using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write(content);
streamWriter.Flush();
streamWriter.Close();
}
如果底层连接关闭,请确保初始化ServicePointManager,它将阻止底层连接关闭:
public Form1()
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
InitializeComponent();
}
所以最后我们有一个看起来像这样的请求:
System.Net.WebRequest webRequest = System.Net.WebRequest.Create("https://directline.botframework.com/v3/directline/conversations");
webRequest.Method = "POST";
string content = " ";
webRequest.Headers.Add("Authorization", "Bearer XXXXXXXXXXXXXX");
webRequest.ContentType = "application/json";
webRequest.ContentLength = content.Length;
using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write(content);
streamWriter.Flush();
streamWriter.Close();
}
System.Net.WebResponse resp = webRequest.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd().Trim();
sr.Close();
resp.Close();
您只需要使用正确的授权标头,否则您将得到
(403)被禁止
来自服务器的响应。
因此,在添加两行代码之后,它也开始使用框架4.5
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;