c# - 如何使 HttpWebRequest 函数异步?

标签 c# .net-core-3.0

我正在尝试使我的函数异步。我该怎么做?它是一个 HttpWebRequest

private void PostToGoogleChat(string json)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_chatUrl);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";


    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        streamWriter.Write(json);
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
}

最佳答案

 HttpClient client = new HttpClient();  

public async Task PostAsync(string actionName, object json)
{
        var content = new StringContent(json.ToString(), Encoding.UTF8,"application/json");
        var resultRoles = await client.PostAsync(new Uri(actionName),content);
}

您是新手,所以我不会详细介绍 HttpClient,但应该重用该实例。尝试对如何实现这一点进行一些 self 研究。

关于c# - 如何使 HttpWebRequest 函数异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633347/

相关文章:

c# - 使用 ObservableAsPropertyHelper 激活/停用

c# - 多态性/亚型违规?

c# - 使用 .NET core 3.0/System.text.Json 解析 JSON 文件

c# - 如何使用 System.Text.Json 库在现有 json 中添加属性?

c# - ef core3 中 HasForeignKey 和 ForSqlServerUseSequenceHiLo 方法的替代方法是什么?

.net-core-3.0 - Microsoft.AspNetCore.Mvc 依赖项和 ASP.NET Core 3

c# - 在.NET Core应用程序中使用WinRT组件

c# - C# 中的自定义日期时间格式

c# - 通过ajax添加部分 View

c# - 覆盖身份验证属性的用途是什么?