将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
相关产品推荐
相关产品推荐

