1

我正在用 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

我该如何解决这个问题?

4

2 回答 2

0

您尝试访问的 URL 不是 URL 编码的。您只能使用 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

于 2013-03-19T09:25:49.327 回答
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>
} 
于 2013-03-19T09:23:29.190 回答