ASHX 处理程序中的异步 Post

Async Post in ASHX Handler

我在使用 ASHX 处理程序时遇到问题。以下代码在本地机器上运行正常,但在服务器上运行不正常。

public void ProcessRequest(HttpContext context)
{
    ...... More code
    // convert class to namevaluecollection
    NameValueCollection formFields = payloadData.ToNameValueCollection();

    using (var client = new WebClient())
    {
        //client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
        client.UploadValuesAsync(new Uri("http://server/accept"), "POST", formFields);
    }
}

我收到以下错误:

Exception type: InvalidOperationException 
    Exception message: An asynchronous operation cannot be started at this time. 
    Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle.
    If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>.
    This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing.
    Instead, the asynchronous method should return a Task, and the caller should await it.

编辑:

有一件事我发现可能是版本对代码库的影响。有人可以确认 UploadValuesAsync 在框架 4.5 和 4.6 上的行为不同

让您的处理程序实现 IHttpAsyncHandler。

这将 post 异步:

Task.Run(() => PostAsync());

更新

经过更多调查,我发现服务器上有一个配置导致了错误。 What's the meaning of "UseTaskFriendlySynchronizationContext"? 问题也很有帮助。

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

提到的键在 machine.config 中的默认值为 False,在 web.config 中它设置为 true。