创建指向包含百分号的文件的链接

时间:2013-03-19 09:15:44

标签: c# asp.net-mvc-3 url

我正在用C#创建一个MVC3 Web应用程序。 我必须实现一个搜索屏幕来显示来自SQL数据库的数据和与这些数据相对应的图片。 在我的详细信息页面中,我创建了一个指向此文档的链接:

        @{
        string fullDocumentPath = "~/History/" + Model.PICTURE_PATH + "/" + Model.PICTURE_NAME.Replace("001", "TIF");
    }
    @if (File.Exists(Server.MapPath(fullDocumentPath)))
    {
        <a href="@Url.Content(fullDocumentPath)" >Click me for the invoice picture.</a>
    }

问题是创建文档的系统(并在数据库中添加了对其路径的引用)选择在许多文件名中使用%。 当我有这个链接:http://localhost:49823/History/044/00/aaau2vab.TIF没关系。创建此链接时:http://localhost:49823/History/132/18/aagn%8ab.TIF失败并显示:

The resource cannot be found. 
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
Requested URL: /History/132/18/aagn�b.TIF

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

使用Url.Encode()方法转义特殊字符:

@{
   string documentDirectoryPath = "~/History/" + Model.PICTURE_PATH + "/";
   string documentName = Model.PICTURE_NAME.Replace("001", "TIF");
}
@if (File.Exists(Server.MapPath(documentDirectoryPath + documentName)))
{
  <a href="@Url.Content(documentDirectoryPath + Url.Encode(documentName))" >Click me for the invoice picture.</a>
} 

答案 1 :(得分:0)

您尝试访问的网址不是网址编码的。您只能使用ASCII字符,因此对于特殊字符,您需要对路径进行UrlEncode。您可以在此列表中看到这些字符的列表以及相应的ASCII字符:

http://www.w3schools.com/tags/ref_urlencode.asp

您可以使用UrlEncode方法将路径字符串转换为URL编码:

http://msdn.microsoft.com/en-us/library/zttxte6w.aspx

如果您想再次解码,可以使用UrlDecode方法:

http://msdn.microsoft.com/en-us/library/6196h3wt.aspx