0

我正在将一些老式代码转换为 ASP.NET MVC,并且遇到了由我们的 URL 格式引起的障碍。我们通过在特殊 URL 路径前加上波浪号来指定 URL 中的缩略图宽度、高度等,如下例所示:

http://www.mysite.com/photo/~200x400/crop/some_photo.jpg

目前,这是由 IIS 中的自定义 404 处理程序解决的,但现在我想/photo/用 ASP.NET 替换并用于System.Web.Routing从传入的 URL 中提取宽度、高度等。

问题是 - 我不能这样做:

routes.MapRoute(
  "ThumbnailWithFullFilename",
  "~{width}x{height}/{fileNameWithoutExtension}.{extension}",
  new { controller = "Photo", action = "Thumbnail" }
);

因为 System.Web.Routing 不允许路由以波浪号​​ (~) 字符开头。

更改 URL 格式不是一种选择……我们从 2000 年起就公开支持这种 URL 格式,并且网络上可能充斥着对它的引用。我可以在路由中添加某种受限通配符吗?

4

1 回答 1

0

您可以编写自定义裁剪路线:

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"
        })
    )
);

在控制器的Thumbnail操作中,Photo您应该在请求时获得所需的一切/~200x400/crop/some_photo.jpg

public ActionResult Thumbnail(
    string fileNameWithoutExtension, 
    string extension, 
    string width, 
    string height
)
{
    ...
}
于 2011-07-17T10:45:10.097 回答