uhsl_m uhsl_m - 5 months ago 33
ASP.NET (C#) Question

How can I use await/async in both a ashx and aspx files on the same site?

I am trying to run an async task in the code-behind for my aspx page. I am using

to run the async method.

However I get the error saying I need to add
<httpRuntime targetFramework="4.5" />
to my webconfig file, but in adding that line, my use of async/await start throw an error in my ashx pages.

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.

Async/await work perfectly fine in the ashx page before adding
<httpRuntime targetFramework="4.5" />
So how can I have async/await working in both kinds of files?


Nowadays when creating ashx files, you probably want them to be asynchronous by default. The framework has support for this by using the new HttpTaskAsyncHandler.

Just inherit from HttpTaskAsyncHandler instead of IHttpHandler.

Then delete the method:

public ProcessRequest(HttpContext context)

and move its code to be inside

public override async Task ProcessRequestAsync(HttpContext context)

where you can take advantage of Tasks