URL 路由适用于 ASP.NET。
您可以创建两条路线,第一条是符合您的语言的路线:
{语言}/{页面}
第二条路线只是
{页面}
在 MVC 中,我们可以创建路由约束,强制语言具有特定值(例如 en、en-us 等)如果可以在常规 ASP.NET WebForms 路由中执行相同的操作,我不肯定.
这里有两篇描述WebForms(非MVC)中路由主题的文章
http://msdn.microsoft.com/en-us/magazine/dd347546.aspx
和
http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx
已编辑以添加代码示例
在我的 Global.asax 中,我注册了以下内容:
void RegisterRoutes(RouteCollection routes)
{
routes.Ignore("{resource}.asxd/{*pathInfo}");
routes.Add(
new Route(
"{locale}/{*url}", //Route Path
null, //Default Route Values
new RouteValueDictionary{{"locale", "[a-z]{2}"}}, //constraint to say the locale must be 2 letters. You could also use something like "en-us|en-gn|ru" to specify a full list of languages
new Utility.Handlers.DefaultRouteHandeler() //Instance of a class to handle the routing
));
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(RouteTable.Routes);
}
我还创建了一个单独的类(请参阅asp.net 4.0 web forms routing - default/wildcard route 作为指南。)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
using System.Web.UI;
namespace SampleWeb.Utility.Handlers
{
public class DefaultRouteHandeler:IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//Url mapping however you want here:
string routeURL = requestContext.RouteData.Values["url"] as string ;
string pageUrl = "~/" + (!String.IsNullOrEmpty(routeURL)? routeURL:"");
var page = BuildManager.CreateInstanceFromVirtualPath(pageUrl, typeof(Page))
as IHttpHandler;
if (page != null)
{
//Set the <form>'s postback url to the route
var webForm = page as Page;
if (webForm != null)
webForm.Load += delegate
{
webForm.Form.Action =
requestContext.HttpContext.Request.RawUrl;
};
}
return page;
}
}
}
这是可行的,因为当 URL 中没有指定区域设置时,Web 表单的默认视图引擎会接管。当使用 2 个字母的语言环境(en?us?等)时,它也可以工作。在 MVC 中,我们可以使用 IRouteConstraint 并进行各种检查,例如确保语言环境在列表中、检查路径是否存在等,但在 WebForms 中,约束的唯一选择是使用 RouteValueDictonary。
现在,我知道代码原样存在问题,无法加载默认文档。所以http://localhost:25436/en/ 不会加载default.aspx 的默认文档,但是http://localhost:25436/en/default.aspx 确实有效。我会留给你解决。
我用子目录对此进行了测试,它可以工作。