0

我正在将一些老派代码转换为ASP.NET MVC,并且遇到了由我们的URL格式引起的障碍。我们的网址用波浪线前缀的特殊URL路径,指定缩略图宽度,高度等,如本例:如何在System.Web.Routing/ASP.NET MVC中匹配以字面波浪号(〜)开头的URL?

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

目前,这是通过在IIS中自定义的404处理器解析,但现在我想用ASP.NET替换/photo/,并使用System.Web.Routing从传入的URL中提取宽度,高度等。

问题是 - 我不能做到这一点:

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

因为System.Web.Routing不允许的路线,开始以波浪号(〜)字符。

更改URL格式不是一个选项...自2000年以来,我们已经公开支持这种URL格式,并且Web可能充斥着对它的引用。我可以为路线添加某种受限制的通配符吗?

回答

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

Photo控制器的Thumbnail动作里面你应该得到的,当你申请你所需要的/~200x400/crop/some_photo.jpg

public ActionResult Thumbnail(
    string fileNameWithoutExtension, 
    string extension, 
    string width, 
    string height 
) 
{ 
    ... 
} 
相关问题