You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将C#中WebRequest实现的PayPal IPN验证代码迁移至HttpClient

将PayPal IPN验证的WebRequest代码迁移到HttpClient

原WebRequest实现代码

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();
}

迁移后的HttpClient完整实现

你当前的代码存在两个关键问题:ContentType设置错误(需和原代码保持一致为application/x-www-form-urlencoded)、编码未匹配原代码的ASCII,同时需要正确处理异步调用。以下是修正后的完整代码:

// 最佳实践:HttpClient建议全局复用,避免每次请求新建实例
using var httpClient = new HttpClient();

var strRequest = "cmd=_notify-validate&" + ipnContext.RequestBody;
// 匹配原代码的ContentType和ASCII编码
var content = new StringContent(strRequest, Encoding.ASCII, "application/x-www-form-urlencoded");

// 异步发送POST请求,需用await关键字
var response = await httpClient.PostAsync(AbstractPricing.PaypalWebAddress, content);
// 可选:确保请求成功,若失败会抛出HttpRequestException
response.EnsureSuccessStatusCode();

// 读取响应内容到字符串,赋值给验证结果
ipnContext.Verification = await response.Content.ReadAsStringAsync();

关键说明

  • 修正ContentType:PayPal IPN验证要求使用application/x-www-form-urlencoded格式,而非你写的text/xml
  • 编码匹配:保持和原代码一致的Encoding.ASCII,避免编码差异导致的验证失败
  • 异步处理:PostAsync和ReadAsStringAsync都是异步方法,必须用await等待完成(如果你的方法是同步的,不推荐用.Result,建议将方法改为异步)
  • HttpClient复用:频繁新建HttpClient会耗尽连接资源,建议将其注册为单例服务(比如在ASP.NET Core中通过AddHttpClient注入)

内容的提问来源于stack exchange,提问作者MyDaftQuestions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:02:41