Convert ASP.NET MVC MvcRouteHandler to ASP.NET Core MVC

289 views Asked by At

I have to port over the following ASP.NET MVC code to .NET Core and I'm stuck on how to do this.

This is my old ASP.NET MVC code:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}",
            defaults: new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
           name: "Cultural",
           url: "{culture}/{controller}/{action}",
           defaults: new { controller = "Home", action = "Index", culture = AppGlobal.DefaultLocale }).RouteHandler = new Routers.CulturalRouteHandler();
    }
}

public class CulturalRouteHandler: MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
    {
        var lang = requestContext.RouteData.Values["culture"].ToString();
        var ci = new CultureInfo(lang);

        // Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
        Thread.CurrentThread.CurrentUICulture = ci;

        return base.GetHttpHandler(requestContext);
    }
}

I converted the routehandler to the following in .NET Core:

public class CulturalRouteHandler : IRouter
{
    private readonly IRouter _defaultRouter;

    public CulturalRouteHandler(IRouter defaultRouter)
    {
        _defaultRouter = defaultRouter;
    }

    public async Task RouteAsync(RouteContext context)
    {
        var lang = context.RouteData.Values["culture"].ToString();
        var ci = new CultureInfo(lang);

        CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
        CultureInfo.CurrentUICulture = ci;

        await _defaultRouter.RouteAsync(context);
    }

    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        return _defaultRouter.GetVirtualPath(context);
    }
}

I'm stuck trying to hook into the route handler for the specific route now.

How would I go about hooking the IRouter into my code for program. cs below:

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
         name: "Cultural",
         pattern: "{culture}/{controller}/{action}",
         defaults: new { controller = "Home", action = "Index", culture = AppGlobal.DefaultLocale };
1

There are 1 answers

0
Rameshkumar On

You change your RouteHandler implementation

public class MyRequestHandler : IRouteHandler
{
  public IHttpHandler GetHttpHandler(RequestContext requestContext)
  {
      return new MyHttpHandler(this, requestContext);
  }
}