简体   繁体   中英

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

I have to port over the following ASP.NET MVC code to .NET Core and I'm stuck on how to go about doing 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 at trying to hook into the routehandler for the specific route now.

Here is my code for program.cs :

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

You change your RouteHandler implementation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM