【问题标题】:Task.Run() in .NET web API Controller / PayPal IPN.NET Web API 控制器/PayPal IPN 中的 Task.Run()
【发布时间】:2021-03-05 08:48:48
【问题描述】:

我正在我的 .NET Core Web API 中实现 PayPal Instant Payment Notifcation (IPN),而来自 PayPal 的参考实现使用 Web API 控制器中的 Task.Run()。

Visual Studio 为该调用提供了一个绿色波浪下划线,并提示该调用不等待。这是在这种特殊情况下使用的,因为这是 PayPal 工作流程的要求。

  1. 收到的 IPN 消息
  2. 启动验证 IPN 消息的任务
  3. 为 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
}

所以我的问题是:

  1. 这是一般的良好做法吗?
  2. 如何避免波浪形下划线提示?

最好的问候

【问题讨论】:

    标签: c# .net-core paypal asp.net-core-webapi paypal-ipn


    【解决方案1】:
    1. 不,这不是一个好习惯,因为未等待的任务(就像您所写的那样)会在调用方法时在没有正确上下文来处理异常或失败的情况下触发并忘记。因此,在您的情况下,消费者只需收到OK (200),因此从他的角度来看,一切都很好。这真的取决于您的工作流程(尤其是 IPNContext 正在做什么)。我个人希望 Accepted (202) 如果你做一个火并忘记并给消费者另一个 Api 来查询我认为没问题的状态。

    2. 您当然可以通过简单地编写来欺骗 Visual Studio:_ = Task.Run(...)

    更好的解决方案是 await 像 Visual Studio 这样的任务正在向您推荐。我不知道为什么 PayPal 示例中缺少 await 的背景,但也许只是问他们。

    Imo 未等待的 Task 总是看起来像代码异味,因为方法调用者无法进行正确的异常/故障处理。

    【讨论】:

    • 为了清楚起见,我在 Receive() 中收到的消息来自 PayPal API。我猜 fire & forget 有理由阻止来自 PayPal 的初始消息超时或阻止他们的 API。他们希望尽快得到答案,因为他们的初始工作已经完成。然后我需要再次调用来验证该初始请求,如果我收到“已验证”,我开始在 ProcessVerificationResponse() 中处理我的内部事情,发送电子邮件,处理其他事情等。我熟悉 Hangfire,但是对于那一项任务来说似乎有点矫枉过正。
    【解决方案2】:

    首先,我想说的是,所有 API 代码示例都应该持保留态度。即使对于大公司,通常也只有一个小团队(或一个人)需要维护六种(或更多)语言的代码示例。在这种情况下,根本不可能拥有高质量的 API 代码示例(或客户端库)。

    在这种情况下,示例代码存在几个问题:

    • WebRequest 实际上在代码中。
    • Task.Run 在 ASP.NET 上。
    • 一劳永逸。

    如果 PayPal 工作流程可以处理它,您可以完全删除 Task.Run。

    如果 PayPal 工作流程需要离线处理,那么正确的解决方案是使用分布式架构。即,将请求参数保存在可靠队列(Azure Storage Queue / Amazon SQS / local on-disk queue)中,并有一个独立的处理器(Azure Function / Amazon Lambda / ASP.NET Core Worker)从队列中读取并发送向 PayPal API 请求。希望使用比WebRequest 更现代的东西。

    我所说的“适当的解决方案”比适用于代码示例的要复杂得多。这也是为什么代码示例通常更多地是关于“这是你如何调用这个 API”而不是关于“这是你的代码应该是这样的”的另一个原因。

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 2019-01-16
      • 2016-07-19
      • 2023-03-07
      • 2021-08-01
      • 1970-01-01
      相关资源
      最近更新 更多