用户可以使用指定文档类型的子文件夹下载位于文件夹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文档,我的客户希望网址如下:
/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}"
});
问题变得有点长,但我想确保,你得到我想要的结果。
答案 0 :(得分:2)
抱歉,ASP.NET路由不支持此功能。如果您想在路径定义中使用多个参数,则必须向控制器操作添加一些代码以组合文件夹和路径名。
另一种方法是使用全能路线:
routes.MapRoute(
"DownloadPriceInformations",
"DownloadPriceInformations/{*folderAndFile}",
new
{
controller = "Document",
action = "DownloadPDF"
});
特殊的{* folderAndFile}参数将包含初始静态文本之后的所有内容,包括所有“/”字符(如果有的话)。然后,您可以在动作方法中接受该参数,它将是“clothes / shirts.pdf”之类的路径。
我还应该注意,从安全角度来看,您需要绝对确定只会处理允许的路径。如果我传入/web.config作为参数,则必须确保我无法下载存储在web.config文件中的所有密码和连接字符串。