用户可以下载位于 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 路由不支持此功能。如果您希望在路由定义中使用多个参数,则必须向 Controller 操作添加一些代码以组合文件夹和路径名称。
另一种方法是使用包罗万象的路线:
routes.MapRoute(
"DownloadPriceInformations",
"DownloadPriceInformations/{*folderAndFile}",
new
{
controller = "Document",
action = "DownloadPDF"
});
特殊的 {*folderAndFile} 参数将包含初始静态文本之后的所有内容,包括所有“/”字符(如果有)。然后,您可以在操作方法中接收该参数,它将是类似“clothes/shirts.pdf”的路径。
我还应该注意,从安全角度来看,您需要绝对确定只处理允许的路径。如果我传入/web.config 作为参数,您必须确保我无法下载存储在您的 web.config 文件中的所有密码和连接字符串。
关于asp.net-mvc - 使用组合 URL 参数映射路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14521630/