C# ASMX web服务能否使用response.BinaryWrite返回响应?
而不是在web方法本身(作为SOAP XML)中返回二进制流(MTOM/Base64编码),例如: 此方法能否以某种方式响应(可能通过C# ASMX web服务能否使用response.BinaryWrite返回响应?,c#,asp.net,web-services,webforms,asmx,C#,Asp.net,Web Services,Webforms,Asmx,而不是在web方法本身(作为SOAP XML)中返回二进制流(MTOM/Base64编码),例如: 此方法能否以某种方式响应(可能通过服务器对象)?: 伪: [WebMethod] public DownloadBinaryWrite(string FileName) ... Response.BinaryWrite(byteArray); 如果要执行BinaryWrite,可能需要编写一个单独的IHttpHandler,而不是web方法。Web方法是面向SOAP内容的,因此,将它们编入自定义
服务器对象)?:
伪:
[WebMethod]
public DownloadBinaryWrite(string FileName)
...
Response.BinaryWrite(byteArray);
如果要执行BinaryWrite,可能需要编写一个单独的IHttpHandler,而不是web方法。Web方法是面向SOAP内容的,因此,将它们编入自定义响应虽然可能,但有点奇怪。是的,这是可能的。您需要将返回类型更改为void,因为我们将直接写入响应,并且您需要手动设置内容类型并结束响应,以便它不会继续处理和发送更多数据
[WebMethod]
public void Download(string FileName)
{
HttpContext.Current.Response.ContentType = "image/png";
HttpContext.Current.Response.BinaryWrite(imagebytes);
HttpContext.Current.Response.End();
}
请注意,WebMethod现在很流行,您应该切换到或(如果您需要SOAP支持)。我需要将其保存在web服务本身中。或者至少在相同的ASMX中(我宁愿避免),我试过了,你是对的。发送soapaction而不返回soap响应似乎有点奇怪。当然不能与普通SOAP客户机互操作,但如果您不需要它,为什么要关心它呢。如果调用方希望使用SOAP(如.NET Web引用),它可能会混淆(不,我还没有尝试那么久;可能会起作用,但似乎不太可能)。Response
无法识别为有效对象。@zig然后使用HttpContext.Current.Response
谢谢!顺便说一句,为什么我们需要HttpContext.Current.Response.End()
?@zig也许可以删除它。但是结束响应可以确保没有额外的数据写入客户端(这可能会损坏文件),并且当前线程将结束,因为它将抛出ThreadAbortException。与此问题类似:
[WebMethod]
public DownloadBinaryWrite(string FileName)
...
Response.BinaryWrite(byteArray);
[WebMethod]
public void Download(string FileName)
{
HttpContext.Current.Response.ContentType = "image/png";
HttpContext.Current.Response.BinaryWrite(imagebytes);
HttpContext.Current.Response.End();
}