可以使用response.BinaryWrite返回ASMX web服务响应

本文关键字:web 服务 响应 ASMX 返回 response BinaryWrite 可以使 | 更新日期: 2023-09-27 18:29:58

而不是在web方法本身中返回二进制流(MTOM/Base64编码)(作为SOAP XML),例如:

[WebMethod]
public byte[] Download(string FileName)
....
return byteArray;

此方法是否可以以某种方式响应(可能通过Server对象)?:

Response.BinaryWrite(byteArray);

伪:

[WebMethod]
public DownloadBinaryWrite(string FileName)
...
Response.BinaryWrite(byteArray);

可以使用response.BinaryWrite返回ASMX web服务响应

是的,这是可能的。您需要将返回类型更改为void,因为我们将直接写入响应,并且您需要手动设置内容类型并结束响应,这样它就不会继续处理和发送更多数据。

[WebMethod]
public void Download(string FileName)
{
    HttpContext.Current.Response.ContentType = "image/png";
    HttpContext.Current.Response.BinaryWrite(imagebytes);
    HttpContext.Current.Response.End();
}

请注意,WebMethod目前并不真正受支持,您应该切换到Web API或WCF(如果您需要SOAP支持)。

如果要执行BinaryWrite,可能需要编写一个单独的IHttpHandler,而不是web方法。Web方法是以SOAP为中心的,所以将它们破解为自定义响应虽然可能,但有点奇怪。