3

I'm having issues with ASHX handler. The following piece of code works correctly on a local machine, but it is not working on the server.

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);
    }
}

I'm getting the following error:

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.

EDIT:

One thing I found that it may be the version impact on the codebase. Can some one confirm that UploadValuesAsync behaves differently on framework 4.5 vs 4.6

cbps
  • 41
  • 6

3 Answers3

1

This will post asynchronously:

Task.Run(() => PostAsync());
Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
1

Update

After more investigation, I found that there is a configuration on the server which was leading to the error. Also What's the meaning of "UseTaskFriendlySynchronizationContext"? question was helpful.

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

The key mentioned is having default value as False in machine.config and in the web.config it set as true.

Community
  • 1
  • 1
cbps
  • 41
  • 6
0

Have your handler implement IHttpAsyncHandler.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • My Http handler is not ASYNC handler but I need to post the values asynchronously to another server to prevent any thread locking. I want to post the data and forget about it. – cbps Apr 12 '16 at 22:04