2016-12-16 10 views
0

Я использую .NET 4.5.2 для веб-приложения, и у меня есть обработчик HTTP, который возвращает обработанное изображение. Я делаю асинхр вызовы обработчика процесса с помощью JQuery и я начал получать следующее сообщение об ошибке:HTTP-обработчик async issue .NET 4.5.2

An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.

Это код обработчика:

 public void ProcessRequest(HttpContext context) 
    { 
     string CaseID = context.Request.QueryString["CaseID"].ToString(); 
     int RotationAngle = Convert.ToInt16(context.Request.QueryString["RotationAngle"].ToString()); 
     string ImagePath = context.Request.QueryString["ImagePath"].ToString(); 

     applyAngle = RotationAngle; 

     string ImageServer = ConfigurationManager.AppSettings["ImageServerURL"].ToString(); 
     string FullImagePath = string.Format("{0}{1}", ImageServer, ImagePath); 

     WebClient wc = new WebClient(); 
     wc.DownloadDataCompleted += wc_DownloadDataCompleted; 
     wc.DownloadDataAsync(new Uri(FullImagePath)); 
    } 

    private void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) 
    { 
     Stream BitmapStream = new MemoryStream(e.Result); 

     Bitmap b = new Bitmap(BitmapStream); 
     ImageFormat ImageFormat = b.RawFormat; 

     b = RotateImage(b, applyAngle, true); 

     using (MemoryStream ms = new MemoryStream()) 
     { 
      if (ImageFormat.Equals(ImageFormat.Png)) 
      { 
       HttpContext.Current.Response.ContentType = "image/png"; 
       b.Save(ms, ImageFormat.Png); 
      } 

      if (ImageFormat.Equals(ImageFormat.Jpeg)) 
      { 
       HttpContext.Current.Response.ContentType = "image/jpg"; 
       b.Save(ms, ImageFormat.Jpeg); 
      } 
      ms.WriteTo(HttpContext.Current.Response.OutputStream); 
     } 
    } 

Любая идея, что это значит, и я мог сделать преодолеть это?

Заранее спасибо.

+0

Преодолеть что? Где код? Что вы пытались сделать, это вызвало это? –

+0

Ваш * обработчик * код. jQuery не имеет ничего общего с обработчиками HTTP, он работает только в браузере. –

+0

Добавленный код, пожалуйста, просмотрите. – user1144596

ответ

0

Ваш код не будет работать так, как он есть, потому что вы создаете WebClient внутри метода ProcessRequest, но не ждите его завершения. В результате клиент будет потерян, как только метод завершится. К моменту поступления ответа, сам запрос завершен. Нет контекста или потока вывода, на который вы можете написать ответ.

Для создания асинхронного обработчика HTTP вам необходимо извлечь из HttpTaskAsyncHandler класса и реализовать ProcessRequestAsync метод:

public class MyImageAsyncHandler : HttpTaskAsyncHandler 
{ 

    public override async Task ProcessRequestAsync(HttpContext context) 
    { 
     //... 
     using(WebClient wc = new WebClient()) 
     { 
      var data=await wc.DownloadDataTaskAsync(new Uri(FullImagePath));   
      using(var BitmapStream = new MemoryStream(data)) 
      { 
       //... 
       ms.WriteTo(context.Response.OutputStream); 
      //... 
      } 
     } 
    } 
} 
+0

Спасибо Panagiotis Kanavos – user1144596