我有一个webforms项目,我使用System.Web.Routing.RouteCollection.MapPageRoute重写URL,但我对一些动态URL有问题。我的URL可能是这样的;
/folder/city-1-2-something.aspx这个的MapPageRoute看起来像这样
routeCollection.MapPageRoute("CompanyCity", "folder/city-{id}-{pid}-{title}.aspx", "~/mypage.aspx");但是我已经意识到有些URL可能是这样的
/folder/city-2-2-something-something.aspx
/folder/city-2-2-something-something-something.aspx
/folder/city-2-2-something-something-something-something.aspx并且我的路由没有正确地处理这些-第一个示例将以结果id = 2-2和pid = something结束,而不是id = 2和pid =2。
{title}并不重要-仅使用{id}和{pid}。我有几个到特定文件夹的类似路由,所以就我所知,我不能使用catch all。但是我如何解决这个问题呢?
发布于 2013-01-10 07:47:12
下面的简单RouteConfig包含一个与所需内容完全匹配的TestRoute。没有更多的东西,所以在某种意义上它是非常糟糕的代码。
但其想法是,现在可以使用正则表达式,它可以很容易地满足您的需求。(命名组"id“(?<id>\d)和"pid”(?<pid>\d)仅匹配数字(\d),因此它们只能匹配到下一个破折号。)
希望能对大家有所启发。
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace InfosoftConnectSandbox
{
public class RouteConfig
{
class TestRoute : RouteBase
{
Regex re = new Regex(@"folder/city-(?<pid>\d)-(?<id>\d)-.*");
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var data = new RouteData();
var url = httpContext.Request.Url.ToString();
if (!re.IsMatch(url))
{
return null;
}
foreach (Match m in re.Matches(url))
{
data.Values["pid"] = m.Groups["pid"].Value;
data.Values["id"] = m.Groups["id"].Value;
}
data.RouteHandler = new PageRouteHandler("~/mypage.aspx");
return data;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return new VirtualPathData(this, "~/mypage.aspx");
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new TestRoute());
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}https://stackoverflow.com/questions/14245058
复制相似问题