locked
WebApi file download via handler RRS feed

  • Question

  • User-588795494 posted

    I am using WebAPI for downloading a .pdf file like this:

    [HttpGet]
    public async Task<HttpResponseMessage> DownloadFile(string id, bool attachment = true)
    {
    HttpResponseMessage result = null;
    
    try
    {
        MyService service = new MyService();
        var bytes = await service.DownloadFileAsync(id);
    
        if (bytes != null)
        {
            result = GetBinaryFile(personalDocument, string.Format("{0}.pdf", id), attachment);
        }
        else
        {
            result = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
    catch (Exception ex)
    {
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "ServerError" });
    }
    
    return result;
    }
    private HttpResponseMessage GetBinaryFile(byte[] bytes, string fileName, bool attachment)
    {
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
       // result.Content = new ByteArrayContent(bytes);
    result.Content = new StreamContent(new System.IO.MemoryStream(bytes));
    //result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
    
    if (attachment)
    {
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    }
    
    result.Content.Headers.ContentDisposition.FileName = fileName;
    result.Content.Headers.ContentLength = bytes.Length;
    return result;
    }

    now, i see that it frozen my site, so i want to change that, and download a pdf file via handler, it's possible to route to IHttpHandler with any changes by client side? by Route attribute?

     

    Sunday, December 27, 2015 1:57 PM

All replies