2013-03-19 98 views
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 

我該如何解決這個問題?

回答

0

使用Url.Encode()方法逃避scpecial字符:

@{ 
    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> 
} 
+0

它會創建類似於「http:// localhost:49823/BusinessCaseHistory/Details /〜%2fHistory%2f132%2f18%2faagn%258ab.TIF」的內容,導致HTTP Error 400 - Bad Request。 – user2185692 2013-03-19 09:31:16

+0

對,那麼你將不得不編碼字符串的名稱部分 – Dima 2013-03-19 09:36:47

+0

這次它給了我'http:// localhost:49823/History/132/18/aagn%258ab.TIF',然後HTTP Error 400 - 錯誤的請求。如果文件名被修改,那麼它就不能被找到。我擔心我必須重新命名數據庫中的所有文件和記錄(其中約有40萬)。 – user2185692 2013-03-19 09:48:07

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

+0

據我瞭解,不僅在數據庫中的名稱,而且文件系統中的文件都帶有%的名稱,所以如果您嘗試解碼名稱,最終會輸入錯誤的名稱。 – Dima 2013-03-19 09:32:05

+0

在數據庫中,我有一列(如'132/21')中的文件路徑和另一列(如'aagn%8ab.001')中的文件名。所以,沒有網址首先解碼。 – user2185692 2013-03-19 09:34:45

+0

@Dima是正確的。 – user2185692 2013-03-19 09:35:31

相關問題