2013-10-25 221 views
1

我已经创建了一个ImageController来从我的项目中的位置提供图像。现在我试图让它从“/Image/file.png”路由到我的控制器,但我似乎无法做到。控制器从来没有被调用过(我在动作的第一行设置了一个断点,它从不中断)。URL不会路由到控制器

我的路线:

routes.MapRoute(
      "Image", 
      "Image/{file}", 
      new { controller = "Image", action = "Render", file = "" } 
     ); 

我ImageController:

public class ImageController : Controller 
{ 
    // 
    // GET: /Image/ 

    public ActionResult Render(string file) 
    { 
     var path = this.getPath(file); 
     System.Diagnostics.Debug.WriteLine(path); 
     if (!System.IO.File.Exists(path)) 
     { 
      return new HttpNotFoundResult(string.Format("File {0} not found.", path)); 
     } 
     return new ImageResult(path); 
    } 

    private string getPath(string file) 
    { 
     return string.Format("{0}/{1}", Server.MapPath("~/Content/Images"), file); 
    } 
} 

为什么不从 “图像/ {}文件的” 我的项目路由到我的控制器?

+0

这可能会有所帮助:http://stackoverflow.com/questions/11257768/asp-net-mvc-route-bypass-staticfile-handler-for-path。从Scott的文章中,您可能可以将* .png,*。gif,* .jpg通配符用于处理这些请求的处理程序。 – TSmith

回答

1

这可能是由于url中的.png扩展名导致请求被路由到静态文件处理程序。你可以尝试通过文件名和后缀为单独的参数,像这样:然后

routes.MapRoute(
     "Image", 
     "Image/{filename}/{suffix}", 
     new { controller = "Image", action = "Render", filename = "", suffix = "" } 
); 

你的控制器动作变为:

public ActionResult Render(string filename, string suffix) 

它应该匹配的URL是这样的:

/Image/file/png