2013-05-29 1 views
1

WebApi의 비동기 파일 업로드 기능에 문제가 있습니다.MultipartFormDataStreamProvider 및 현재 HttpContext 보존

현재 공급자를 사용하여 파일을 저장할 수 있지만 서비스 (_myService)를 사용하여 업로드 한 파일의 파일 이름을 기록하려고합니다. 서비스 내부에서는 다른 서비스를 사용하여 현재 UserId를 가져옵니다. 현재 HttpContext를 사용하여이를 수행합니다. 불행히도 현재 HttpContext 새 작업 스레드 내에서 손실 된 것 같습니다.

TaskScheduler.FromCurrentSynchronizationContext()를 작업의 두 번째 매개 변수로 추가하려고 시도했지만 아무 효과가 없습니다. 그게 나에게주는 것을 정말로 모르겠다. 그래서 새로운 스레드에 걸쳐 HTTP 컨텍스트를 얻는 방법이 필요합니다. 나는 이것을 어떻게 얻을 수 있을까?

답변

3

마지막으로 해결 방법을 발견 했으므로 좋았을 것처럼 깨끗하지 않습니다. 기본적으로 컨텍스트의 사본을 별도의 변수에 보관하고 이것을 클로저에 전달합니다. 이것이 최선의 관행인지 아닌지는 잘 모르지만 작동합니다!

var currentHttpContext = HttpContext.Current; 

     var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(
     t => 
     { 
      // Enquiry service requires access to authentication data which is retrieved via http context. 
      // Not ideal but set the http context here so it available on the new thread.      
      HttpContext.Current = currentHttpContext; 

      if (t.IsFaulted || t.IsCanceled) 
       throw new HttpResponseException(HttpStatusCode.InternalServerError); 

      var fileInfo = provider.FileData.FirstOrDefault(); 
      if (fileInfo == null) 
       throw new HttpResponseException(HttpStatusCode.InternalServerError); 

      _myService.LogUploadedFile(fileInfo.LocalFileName); 

      var uploadModel = new FileUpModel { success = true }; 
      return uploadModel; 
     }); 

     return task;