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 
) 
{ 
    ... 
} 
相關問題