I am developing concepts for a new project where I need to support multilingual URLs. Ideally, all URLs should be in the user's native language. Therefore, we do not want to use domain.com/en/contact and domain.com/es/contact , but we like domain.com/contact and domain.com/contactar (contactar - for communicating in Spanish). Internally, both must be routed to the same ContactController class.
This may be due to the addition of several static routes to Global.asax.cs for each language, but wed how to make it very dynamic, and would like the system user to be able to change the translation of URLs through the content management system. Therefore, we need some kind of dynamic mapping from URLs to controllers and actions.
Having studied the source code of MVC3, I realized that the ProcessRequestInit MvcHandler method is responsible for determining which controller should be created. It just looks up the controller name in RouteData. One way to override standard MVC routing is to create a simple default route that uses a custom RouteHandler. This RouteHandler forces MVC to use my own subclass version of MvcHandler, which overrides the ProcessRequestInit method. This overridden method inserts my own dynamically found controller and action into RouteData before moving on to the original ProcessRequestInit.
Ive tried this:
Global.asax.cs
routes.Add(
new Route("{*url}", new MultilingualRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Default", action = "Default" })
}
);
MultilingualRouteHandler.cs
public class MultilingualRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MultilingualMVCHandler(requestContext);
}
}
MultilingualMvcHandler.cs
public class MultilingualMVCHandler : MvcHandler
{
public MultilingualMVCHandler(RequestContext context) : base(context)
{
}
protected override void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory)
{
if (RequestContext.RouteData.Values.ContainsKey("controller"))
{
RequestContext.RouteData.Values.Remove("controller");
}
if (RequestContext.RouteData.Values.ContainsKey("action"))
{
RequestContext.RouteData.Values.Remove("action");
}
RequestContext.RouteData.Values.Add("controller", "Product");
RequestContext.RouteData.Values.Add("action", "Index");
base.ProcessRequestInit(httpContext, out controller, out factory);
}
}
, . , , ASP.NET MVC3, . , ProcessRequestInit MvcHandler , , . Ive , .
, , , . , System.Web.Mvc.dll. , RTM.
- ASP.NET MVC, , URL-? , , - RouteCollection * Application_Start *, , .
, Ive .