【发布时间】:2021-03-05 08:48:48
【问题描述】:
我正在我的 .NET Core Web API 中实现 PayPal Instant Payment Notifcation (IPN),而来自 PayPal 的参考实现使用 Web API 控制器中的 Task.Run()。
Visual Studio 为该调用提供了一个绿色波浪下划线,并提示该调用不等待。这是在这种特殊情况下使用的,因为这是 PayPal 工作流程的要求。
- 收到的 IPN 消息
- 启动验证 IPN 消息的任务
- 为 1 返回 OK。
[HttpPost]
public async Task<IActionResult> Receive()
{
IPNContext context = new IPNContext()
{
IPNRequest = Request
};
using (var ms = new StreamReader(context.IPNRequest.Body))
{
context.RequestBody = await ms.ReadToEndAsync();
}
//Fire and forget verification task
Task.Run(() => VerifyTask(context)); // Send back the same IPN-message with added "_notify-validate"-parameter and then continue to process from there
//Reply back a 200 code
return Ok();
}
private void VerifyTask(IPNContext ipnContext)
{
try
{
var verificationRequest = WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr");
//Set values for the verification request
verificationRequest.Method = "POST";
verificationRequest.ContentType = "application/x-www-form-urlencoded";
//Add cmd=_notify-validate to the payload
string strRequest = "cmd=_notify-validate&" + ipnContext.RequestBody;
verificationRequest.ContentLength = strRequest.Length;
//Attach payload to the verification request
using (StreamWriter writer = new StreamWriter(verificationRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(strRequest);
}
//Send the request to PayPal and get the response
using (StreamReader reader = new StreamReader(verificationRequest.GetResponse().GetResponseStream()))
{
ipnContext.Verification = reader.ReadToEnd();
}
}
catch (Exception exception)
{
_logger.LogDebug($"IPN-REQUEST::VerifyTask::ERROR => {exception.Message}");
}
ProcessVerificationResponse(ipnContext); // That is my internal processing of the Event
}
所以我的问题是:
- 这是一般的良好做法吗?
- 如何避免波浪形下划线提示?
最好的问候
【问题讨论】:
标签: c# .net-core paypal asp.net-core-webapi paypal-ipn