2014-11-18 5 views
0

웹 API 2를 사용하여 파일을 다운로드하려고합니다. 그러나 브라우저에 URL을 직접 입력하면 브라우저에서 "웹 페이지를 사용할 수 없습니다"라는 메시지가 나타납니다. 나는 사용자 지정 작업파일 다운로드 web api 2

public class FileActionResult : IHttpActionResult 
    { 
     public FileActionResult(string data) 
     { 
      this.Data = data; 
     } 

     public string Data { get; private set; } 

     public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
     { 
      string tempFolderPath = HttpContext.Current.Server.MapPath("~/api/tempfiles"); 
      HttpResponseMessage response = new HttpResponseMessage(); 
      Guid guid = Guid.NewGuid(); 
      string folderPath = Path.Combine(tempFolderPath, guid.ToString()); 
      if(!Directory.Exists(folderPath)) 
      { 
       Directory.CreateDirectory(folderPath); 
      } 
      string filePath = Path.Combine(folderPath, guid.ToString() + ".json"); 
      File.WriteAllText(filePath, Data); 
      string zipFile = folderPath + ".zip"; 
      ZipFile.CreateFromDirectory(folderPath, zipFile); 
      response.Content = new StreamContent(File.OpenRead(zipFile)); 
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); 
      response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
      { 
       FileName = "file.zip", 
       DispositionType = "attachment" 
      }; 
      return Task.FromResult(response); 
     } 
    } 

다음 작성한

나는 여기에 어떤 문제가 있는지 모르겠습니다. 누가 이걸 도와 줄 수 있니?

편집 Google-PostMan을 사용하여 방법을 확인하면 적절한 응답이 표시됩니다. 어떻게 브라우저가 파일을 다운로드하도록 강요합니까? 감사합니다.

+0

이 코드는 나에게 좋아 보인다. WebAPI 방법에 문제가있을 수 있습니까? 거기에 적절한 HTTP 동사를 사용 하시겠습니까? – vzayko

+0

HTTPGet을 사용하고 있습니다. –

+0

"페이지를 사용할 수 없음"이란 잘못된 메서드 호출을 유발할 수 있습니다. 즉, 메서드가 GET을 기대하지만 POST 또는 잘못된 메서드 매개 변수 수 또는 사용자 지정 라우팅 문제를 사용합니다. F12 브라우저 도구를 사용하여 전화를 걸고 입력 매개 변수 및 서버 응답을 분석하십시오. – vzayko

답변

1

코드가 제대로 동작합니다. 그러나 Telerik Control과 관련된 문제였습니다. 내 웹 사이트에서 Telerik 컨트롤을 사용하고 있습니다. Telerik은 파일 다운로드 중에 압축을 수행하고있었습니다. URL을 무시하면 제대로 작동합니다.

<sectionGroup name="telerik.web.ui"> 
     <section name="radCompression" type="Telerik.Web.UI.RadCompressionConfigurationSection, Telerik.Web.UI" allowDefinition="MachineToApplication" requirePermission="false"/> 
    </sectionGroup> 
    </configSections> 

    <telerik.web.ui> 
    <radCompression> 
     <excludeHandlers> 
     <add handlerPath="some path" matchExact="false"/> 
     </excludeHandlers> 
    </radCompression> 
    </telerik.web.ui> 
관련 문제