ASHX处理程序中的异步POST

3

我遇到了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上的行为是否不同吗?

3个回答

1

更新

经过更多的调查,我发现服务器上有一个配置导致了这个错误。同时“UseTaskFriendlySynchronizationContext”的意思是什么?这个问题也很有帮助。

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

机器配置(machine.config)中提到的关键字默认值为False,在web.config中设置为true。

1

这将异步发送:

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

0

让您的处理程序实现IHttpAsyncHandler接口。


我的Http处理程序不是异步处理程序,但我需要以异步方式将值发布到另一台服务器,以防止任何线程锁定。我希望能够发布数据并忘记它。 - cbps

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接