HTTP 处理程序异步问题 .NET 4.5.2

HTTP Handler async issue .NET 4.5.2

我正在将 .NET 4.5.2 用于 Web 应用程序,并且我有一个 HTTP 处理程序,returns 处理过的图像。我正在使用 jQuery 对进程处理程序进行异步调用,我开始收到以下错误:

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);
        }
    }

知道这意味着什么吗?我可以做些什么来克服这个问题?

提前致谢。

您的代码无法按原样运行,因为您在 ProcessRequest 方法中创建了一个 WebClient,但没有等待它完成。因此,客户端将在方法完成后立即被孤立。当响应到达时,请求本身已经完成。没有您可以写入响应的上下文或输出流。

要创建异步 HTTP 处理程序,您需要从 HttpTaskAsyncHandler class and implement the 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);
             //...
          }
      }
   }
}