سؤال

I have created a Web Api that returns an HttpResponseMessage in which the content is set to a PDF file. If I call the Web Api directly it works great and the PDF is rendered in the browser.

response.Content = new StreamContent(new FileStream(pdfLocation, FileMode.Open, FileAccess.Read));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        response.Headers.ConnectionClose = true;
        return response;

I have an MVC Client that would like to do contact the Web Api, request the Pdf file then render it to the user in the same way as above.

Unfortunately, I'm not sure where the problem is but even though I set the the content-type:

response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

When I click on the link that calls the web api, I get a text rendering of the HttpResponseMessage.

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Connection: close Content-Disposition: attachment Content-Type: application/pdf }

I'm thinking that the Client Application is missing some setting that will allow it to render the PDF like my Web Api does...

Any help would be appreciated. Thanks

هل كانت مفيدة؟

المحلول

After hours of Google searching as well as trial and error, I have resolved the issue here.

instead of setting the content of the response to a StreamContent I have changed it to ByteArrayContent on the Web Api side.

byte[] fileBytes = System.IO.File.ReadAllBytes(pdfLocation);
response.Content = new ByteArrayContent(fileBytes);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

By doing it this way, my MVC 4 application is able to download the PDF using a WebClient and the DownloadData method.

internal byte[] DownloadFile(string requestUrl)
{
    string serverUrl = _baseAddress + requestUrl;
    var client = new System.Net.WebClient();
    client.Headers.Add("Content-Type", "application/pdf");
    return client.DownloadData(serverUrl);
}

The Byte[] array that is returned can easily be converted to a MemoryStream before returning the File for output...

Response.AddHeader("Content-Disposition", "inline; filename="+fileName);
MemoryStream outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(outputStream, "application/pdf");

I hope this can be useful to others as I have wasted a lot of time to get it working.

نصائح أخرى

Just return PhysicalFileResult and use HttpGet method ,url will open pdf file

public ActionResult GetPublicLink()



{
            path = @"D:\Read\x.pdf";
            return new PhysicalFileResult(path, "application/pdf");
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top