你可以使用可选语言URL段来设置MapRoute,以下是一个示例代码:
在Global.asax.cs文件中:
using System.Web.Mvc;
using System.Web.Routing;
namespace YourNamespace
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
在RouteConfig.cs文件中:
using System.Web.Mvc;
using System.Web.Routing;
namespace YourNamespace
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// 设置可选语言URL段
routes.MapRoute(
name: "Language",
url: "{language}/{controller}/{action}/{id}",
defaults: new { language = "en", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// 添加其他路由规则
// ...
// 默认路由规则
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
在HomeController.cs文件中:
using System.Web.Mvc;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
在Views文件夹中创建Home文件夹,并在其中添加Index.cshtml视图文件。
使用上述代码,你可以将可选的语言URL段添加到你的路由规则中。例如,访问/en/Home/Index将调用HomeController的Index方法,并返回Index.cshtml视图。如果不提供语言URL段,则默认为英语(en)。
希望对你有所帮助!