Search code examples
c#asp.netweb-serviceswebformsasmx

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


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

Solution

  • 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).