can an ASMX web service response back with Response.BinaryWrite?

4.5k Views Asked by At

Instead of returning a binary stream (MTOM/Base64 encoded) in the web-method itself (as SOAP XML) e.g:

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

Can this method respond somehow with (maybe via the Server object)?:

Response.BinaryWrite(byteArray);

Pseudo:

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

There are 2 best solutions below

11
On BEST ANSWER

Yes, it is possible. You need to change the return type to void since we're going to be writing directly to the response, and you need to manually set the content type and end the response so that it doesn't continue processing and send more data.

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

Note that WebMethod is not really supported these days, you should be switching to Web API or WCF (if you need SOAP support).

1
On

If you want to do BinaryWrite you probably want to write a separate IHttpHandler instead of a web method. Web methods are oriented around SOAP stuff, so hacking them into custom responses, while possible, is kind of odd.