Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async RouteBase in ASP.NET with GetRouteDataAsync and GetVirtualPathAsync?

I have a custom ASP.NET Route that has IO operations in it. For now, assume these IO operations can't be cached (i.e. too big).

In a way I'm looking for a an AsyncRouteBase class with

public async override Task<RouteData> GetRouteDataAsync(HttpContextBase httpContext)
public async override Task<VirtualPathData> GetVirtualPathAsync(RequestContext requestContext, RouteValueDictionary routeValues);
  • Does something similar already exist? (can't find it)
  • Is there any place within the ASP.NET pipeline where I can create this myself?

I'm using ASP.NET MVC 5.2.3.0

like image 402
Dirk Boer Avatar asked Jul 18 '15 09:07

Dirk Boer


1 Answers

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.

like image 57
Akash Kava Avatar answered Oct 26 '22 04:10

Akash Kava