【问题标题】:Async Post in ASHX HandlerASHX 处理程序中的异步发布
【发布时间】:2016-04-20 23:57:19
【问题描述】:

我在使用 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 上的行为不同

【问题讨论】:

    标签: c# asp.net asynchronous webclient httphandler


    【解决方案1】:

    这将异步发布:

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

    【讨论】:

      【解决方案2】:

      更新

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

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

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

      【讨论】:

        【解决方案3】:

        让您的处理程序实现 IHttpAsyncHandler。

        【讨论】:

        • 我的 Http 处理程序不是 ASYNC 处理程序,但我需要将值异步发布到另一台服务器以防止任何线程锁定。我想发布数据并忘记它。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多