【问题标题】:Map routes with combined URL parameter使用组合 URL 参数映射路线
【发布时间】:2013-01-25 12:15:49
【问题描述】:

用户可以下载位于文件夹PriceInformations 中的价格信息PDF,其中包含指定文档类型的子文件夹,例如:

/PriceInformations/Clothes/Shoes.pdf
/PriceInformations/Clothes/Shirts.pdf
/PriceInformations/Toys/Games.pdf
/PriceInformations/Toys/Balls.pdf

考虑在 Controller Document 中执行以下操作以下载这些 PDF:

// Filepath must be like 'Clothes\Shoes.pdf'
public ActionResult DownloadPDF(string filepath)
{
    string fullPath = Path.Combine(MyApplicationPath, filepath);

    FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);

    return base.File(fileStream, "application/pdf");
}

为了获取 PDF 文档,我的客户希望 URL 类似于:

/PriceInformations/Clothes/Shoes.pdf

我可以轻松地为这种情况创建一个重载函数:

public ActionResult DownloadPDF(string folder, string filename)
{
    return this.DownloadPDF(Path.Combine(folder, filename);
}

像这样映射它

routes.MapRoute(
    "DownloadPriceInformations",
    "DownloadPriceInformations/{folder}/{filename}",
    new
    {
        controller = "Document",
        action = "DownloadPDF"
    });

但我很好奇是否可以在没有重载函数的情况下工作并将这种情况映射到 Global.asax 中的RegisterRoutes,以便能够从多个参数中创建一个参数:

routes.MapRoute(
    "DownloadPriceInformations",
    "DownloadPriceInformations/{folder}/{filename}",
    new
    {
        controller = "Document",
        action = "DownloadPDF",
        // How to procede here to have a parameter like 'folder\filename'
        filepath = "{folder}\\{filename}"
    });

问题变得有点长,但我想确保你得到我想要的结果。

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-routing url-routing


【解决方案1】:

抱歉,ASP.NET 路由不支持此功能。如果你想在路由定义中有多个参数,你必须在控制器操作中添加一些代码来组合文件夹和路径名。

另一种方法是使用包罗万象的路线:

routes.MapRoute(
    "DownloadPriceInformations",
    "DownloadPriceInformations/{*folderAndFile}",
    new
    {
        controller = "Document",
        action = "DownloadPDF"
    });

并且特殊的 {*folderAndFile} 参数将包含初始静态文本之后的所有内容,包括所有“/”字符(如果有)。然后,您可以在您的操作方法中接收该参数,它将是类似“clothes/shirts.pdf”的路径。

我还应该注意,从安全角度来看,您需要绝对确定只会处理允许的路径。如果我将 /web.config 作为参数传入,您必须确保我无法下载存储在您的 web.config 文件中的所有密码和连接字符串。

【讨论】:

  • 谢谢四位您的回答,我来了分离文件夹和文件名。感谢您的安全提示,但我的操作 DownloadPDF 已经只在某个文件夹中有效,所以 /PriceInformations/Clothes/Shoes.pdf 转到 /AppData/Documents//PriceInformations/Clothes/Shoes.pdf
猜你喜欢
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多