[英]How do I match a URL starting with a literal tilde character (~) in System.Web.Routing / ASP.NET MVC?
我正在將一些老式代碼轉換為 ASP.NET MVC,並且遇到了由我們的 URL 格式引起的障礙。 我們通過在特殊的 URL 路徑前加上波浪號來指定 URL 中的縮略圖寬度、高度等,如下例所示:
http://www.mysite.com/photo/~200x400/crop/some_photo.jpg
At the moment, this is resolved by a custom 404 handler in IIS, but now I want to replace /photo/
with an ASP.NET and use System.Web.Routing
to extract the width, height, etc. from the incoming URL.
問題是 - 我不能這樣做:
routes.MapRoute(
"ThumbnailWithFullFilename",
"~{width}x{height}/{fileNameWithoutExtension}.{extension}",
new { controller = "Photo", action = "Thumbnail" }
);
因為 System.Web.Routing 不允許路由以波浪號 (~) 字符開頭。
更改 URL 格式不是一種選擇......我們自 2000 年以來就公開支持此 URL 格式,並且 web 可能是對它的引用。 我可以在路由中添加某種受限通配符嗎?
您可以編寫自定義裁剪路線:
public class CropRoute : Route
{
private static readonly string RoutePattern = "{size}/crop/{fileNameWithoutExtension}.{extension}";
private static readonly string SizePattern = @"^\~(?<width>[0-9]+)x(?<height>[0-9]+)$";
private static readonly Regex SizeRegex = new Regex(SizePattern, RegexOptions.Compiled);
public CropRoute(RouteValueDictionary defaults)
: base(
RoutePattern,
defaults,
new RouteValueDictionary(new
{
size = SizePattern
}),
new MvcRouteHandler()
)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
if (rd == null)
{
return null;
}
var size = rd.Values["size"] as string;
if (size != null)
{
var match = SizeRegex.Match(size);
rd.Values["width"] = match.Groups["width"].Value;
rd.Values["height"] = match.Groups["height"].Value;
}
return rd;
}
}
你會像這樣注冊:
routes.Add(
new CropRoute(
new RouteValueDictionary(new
{
controller = "Photo",
action = "Thumbnail"
})
)
);
在Photo
controller 的Thumbnail
操作中,您應該在請求/~200x400/crop/some_photo.jpg
時獲得所需的一切:
public ActionResult Thumbnail(
string fileNameWithoutExtension,
string extension,
string width,
string height
)
{
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.