2015-08-28 65 views
2

這是我學習實現從網頁API下載文件中的link,我試圖下載文件,這些URL如何使用URL末尾的點來調用Web API操作?

http://localhost:49932/api/simplefiles/1.zip < - 不工作時,抱怨沒有找到 http://localhost:49932/api/simplefiles/1 <方法 - 能調用動作名稱,但爲什麼?

我知道一些與「.zip」擴展名相關的URL,導致失敗,但我只是沒有得到它,不知道什麼是錯的,任何人都可以解釋一下嗎?

接口

public interface IFileProvider 
{ 
    bool Exists(string name); 
    FileStream Open(string name); 
    long GetLength(string name); 
} 

控制器

public class SimpleFilesController : ApiController 
{ 
    public IFileProvider FileProvider { get; set; } 

    public SimpleFilesController() 
    { 
     FileProvider = new FileProvider(); 
    } 

    public HttpResponseMessage Get(string fileName) 
    { 
     if (!FileProvider.Exists(fileName)) 
     { 
      throw new HttpResponseException(HttpStatusCode.NotFound); 
     } 

     FileStream fileStream = FileProvider.Open(fileName); 
     var response = new HttpResponseMessage(); 
     response.Content = new StreamContent(fileStream); 
     response.Content.Headers.ContentDisposition 
      = new ContentDispositionHeaderValue("attachment"); 
     response.Content.Headers.ContentDisposition.FileName = fileName; 
     response.Content.Headers.ContentType 
      = new MediaTypeHeaderValue("application/octet-stream"); 
     response.Content.Headers.ContentLength 
       = FileProvider.GetLength(fileName); 
     return response; 
    } 
} 

WebAPIConfig

config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{filename}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 
+1

您是否嘗試過通過'http://本地主機:49932/API/simplefiles/1.zip /' –

+0

看看這個線程,它描述了這個問題:http://stackoverflow.com/questions/429963/the-resource-cannot-be-found-error-when-there-is-a-dot-at -the-結束的-UR –

回答

1

IIS,默認情況下,BL ocks可以訪問它無法識別的任何文件類型。如果URL中包含一個點(。),則IIS會使用其文件名並阻止訪問。

要允許IIS網站上的URL(可能是用於MVC路由路徑中的域名/電子郵件地址等)中的點,您必須進行一些更改。

快速修復

一個簡單的選擇是一個/追加到末尾。這告訴IIS它的文件路徑而不是文件。

http://localhost:49932/api/simplefiles/1.zip變成http://localhost:49932/api/simplefiles/1.zip/

但是,這並不理想:手動鍵入URL的用戶可能會忽略前導斜槓。

你可以告訴IIS不加入以下打擾你:

<system.webServer> 
     <modules runAllManagedModulesForAllRequests="true" /> 
<system.webServer> 

檢查此鏈接:http://average-joe.info/allow-dots-in-url-iis/

相關問題