1

我创建了一个 ImageController 来从我的项目中的某个位置提供图像。现在我试图让它从“/Image/file.png”路由到我的控制器,但我似乎无法正确处理。控制器从未被调用(我在操作的第一行设置了一个断点,它从不中断)。

我的路线:

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

我的图像控制器:

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

为什么我的项目没有从“Images/{file}”路由到我的控制器?

4

1 回答 1

1

这可能是因为 url 中的 .png 扩展名导致请求被路由到静态文件处理程序。您可以尝试将文件名和后缀作为单独的参数传递,如下所示:

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

然后您的控制器操作变为:

public ActionResult Render(string filename, string suffix)

它应该匹配这样的网址:

/Image/file/png
于 2013-10-25T13:39:57.507 回答