ASHX Handler中的Async Post

时间:2016-04-12 21:51:53

标签: c# asp.net asynchronous webclient httphandler

我遇到了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在framework 4.5 vs 4.6

上的行为有所不同

3 个答案:

答案 0 :(得分:0)

这将异步发布:

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

答案 1 :(得分:0)

<强>更新

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

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

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

答案 2 :(得分:-1)

让你的处理程序实现IHttpAsyncHandler。