我的代码过go 运行得很好,这是

var verificationRequest2 = WebRequest.Create(AbstractPricing.PaypalWebAddress);
verificationRequest2.Method = "POST";
verificationRequest2.ContentType = "application/x-www-form-urlencoded";

var strRequest = "cmd=_notify-validate&" + ipnContext.RequestBody;
verificationRequest2.ContentLength = strRequest.Length;

using (var writer = new StreamWriter(verificationRequest2.GetRequestStream(), Encoding.ASCII))
{
    writer.Write(strRequest);
}

using (var reader = new StreamReader(verificationRequest2.GetResponse().GetResponseStream()))
{
    ipnContext.Verification = reader.ReadToEnd();
}

问题是,WebClient已经过时了,我需要将其转换为HttpClient

我不知道怎么把这个换算成HttpClient...我有tried

var verificationRequest = new HttpClient();
var content = new StringContent(strRequest, Encoding.UTF8, "text/xml");
var response= verificationRequest.PostAsync(AbstractPricing.PaypalWebAddress, content);
//help here please

我不知道如何做最后一位-我如何使用HttpClient获得验证

推荐答案

您可以用与Web客户端完全相同的方式构造请求

class AbstractPricing {
  // Replace this with the actual PayPal web address
  public static string PaypalWebAddress {
    get;
  } = "https://www.example.com/paypal-endpoint";
}

class IpnContext {
  public string RequestBody {
    get;
    set;
  }
  public string Verification {
    get;
    set;
  }
}

// Actual code here, previous code just for testing
var paypalWebAddress = AbstractPricing.PaypalWebAddress;
var strRequest = "cmd=_notify-validate&" + ipnContext.RequestBody;

using (HttpClient httpClient = new HttpClient())
{
    // Create the HTTP content with the correct content type
    var content = new StringContent(strRequest, Encoding.ASCII, "application/x-www-form-urlencoded");

    // Make the POST request
    HttpResponseMessage response = await httpClient.PostAsync(paypalWebAddress, content);

    // Check if the request was successful
    if (response.IsSuccessStatusCode)
    {
        // Read the response content
        ipnContext.Verification = await response.Content.ReadAsStringAsync();
    }
    else
    {
        // Handle the error, e.g., log or throw an exception
        Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
    }

    // do something with ipnContext here
}

Csharp相关问答推荐

无法更改或使用C#(WinForms.NET)中的全局变量

在C#WinUI中,一个关于System的崩溃."由于未知原因导致执行不例外"

使用Audit.EntityFramework,我如何将外键的值设置为相关实体上的属性?

默认情况下,.NET通用主机(Host.CreateDefaultBuilder)中是否包含UseConsoleLifetime?

使用C#HttpClient以多部分形式数据发送带有非ASCII文件名的文件的问题

MS Graph v5.42.0:在寻呼消息时更改页面大小

为具有实体框架后端的Reaction项目 Select 正确的Visual Studio模板

.NET并发词典交换值

依赖项注入、工厂方法和处置困境

ASP.NET Core MVC将值从视图传递到控制器时出现问题

LINQ to Entities中的加权平均值

EF核心新验证属性`DeniedValues`和`StringCompison`不起作用

获取混淆&Quot;模糊引用&Quot;错误

错误:此版本的Visual Studio无法打开以下项目

为什么在使用JsonDerivedType序列化泛型时缺少$type?

在Unity C#中按键点击错误的参数

为什么C#中的类型别名不能在另一个别名中使用?

如何对列表<;列表>;使用集合表达式?

如何根据分割文本的块数来计算文本的大小?

不寻常的C#语法