Async RouteBase in ASP.NET with GetRouteDataAsync and GetVirtualPathAsync? Async RouteBase in ASP.NET with GetRouteDataAsync and GetVirtualPathAsync? asp.net asp.net

Async RouteBase in ASP.NET with GetRouteDataAsync and GetVirtualPathAsync?


You cannot create AsyncRouteBase, because routes used by ASP.NET MVC are synchronous. You have to understand that in order for you to create async methods, someone must consume them asynchronously, you can't magically make everything asynchronous by adding async method.

Routing can't be asynchronous for various reasons, Routes are cached and are only created once at time of executing first request. Beware, routes are cached, they will not change and they can't be changed in runtime because they are executed first, if Routing will make async db calls, every request will have to wait for Routing condition to fulfill which will slow down entire application.

And you mostly do not need AsyncRouteBase, instead you can create Async Route Handler.

public class AsyncRouteHandler : IRouteHandler{    IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)    {        return new AsyncHttpHandler();    }}public class AsyncHttpHandler : HttpTaskAsyncHandler{    public override async Task ProcessRequestAsync(HttpContext context)    {            }}

However, using MVC pipeline inside this will require lots of work, but you can easily ignore that and service your response from here. You can use controller factory inside this and create your methods to execute what you need.

Other alternative is to easily use MEF or other form of DI to manage your larger code base and invoke respective methods inside AsyncHttpHandler.


Unfortunately, There is no way to override a non async method with an async one. I think your best bet is to have an async non override method and call into that from the non async one like:

public override RouteData GetRouteData(HttpContextBase httpContext) {    return GetRouteDataAsync(httpContext);    //return await GetRouteDataAsync(httpContext);}public async override Task<RouteData> GetRouteDataAsync(HttpContextBase httpContext){    //operations here}

Note: this can cause problems though. If the original code didn't expect for any async code to be executing introducing this pattern could break expectations. Avoid it if possible.

As an advice, See Simplify Asynchronous Programming with Tasks