gpt4 book ai didi

c# - 通过 IHttpAsyncHandler 发送文件时遇到问题

转载 作者:行者123 更新时间:2023-11-30 14:20:10 25 4
gpt4 key购买 nike

我正在使用 IHttpHandler 调用 Web 服务并将生成的 byte[] 作为下载的文件附件返回给客户端。这工作正常,但是当我尝试将 IHttpHandler 更改为 IHttpAsyncHandler 时,文件下载对话框显示,但文件没有开始/完成下载。我做错了什么?

<%@ WebHandler Language="C#" Class="PreviewPDF"  %>

using System;
using System.Web;

public class PreviewPDF : IHttpAsyncHandler
{
public void ProcessRequest(HttpContext context)
{
}

public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
{
string data = "some data";

using (WebService.RequestService service = new WebService.RequestService())
{
AsyncCallback callback = new AsyncCallback(EndProcessRequest);
return service.BeginGetFile(data, callback, context);
}
}
public void EndProcessRequest(IAsyncResult result)
{
HttpContext context = result.AsyncState as HttpContext;
byte[] wsoutput;
using (WebService.RequestService service = new WebService.RequestService())
{
wsoutput = service.EndGetFile(result);
}

context.Response.ContentType = "application/octet-stream";
context.Response.ContentEncoding = System.Text.Encoding.Unicode;
context.Response.AddHeader("Content-Disposition", "attachment; filename=attachment.pdf");
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(wsoutput))
{
ms.WriteTo(context.Response.OutputStream);
}
context.Response.Flush();
}


public bool IsReusable {
get {
return false;
}
}
}

最佳答案

关于您的代码的一些评论:

  1. 您需要在调用 BeginGetFile 的同一服务实例上调用 EndGetFile
  2. 您需要传递 cb 作为 AsyncCallBack 而不是 EndProcessRequest

下面是考虑了这些评论的代码:

private class State
{
public HttpContext Context { get; set; }
public RequestService Service { get; set; }
}

public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}

public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
{
// Don't use using block or it will dispose the service before you can call EndGetFile
var state = new State
{
Service = new RequestService(),
Context = context
};
// Pass cb here and not EndProcessRequest
return state.Service.BeginGetFile(cb, state);
}

public void EndProcessRequest(IAsyncResult result)
{
State state = result.AsyncState as State;
// Be carefull as this may throw: it is best to put it in a try/finally block
// so that you dispose properly of the service
byte[] buffer = state.Service.EndGetFile(result);
state.Service.Dispose();
state.Context.Response.ContentType = "application/octet-stream";
state.Context.Response.AddHeader("Content-Disposition", "attachment; filename=attachment.pdf");
// Write directly into the output stream, and don't call Flush
state.Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}

public bool IsReusable
{
get { return false; }
}

关于c# - 通过 IHttpAsyncHandler 发送文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1632782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com