3

A client will be issuing a GET request to our web api service, and we need to respond to that request with the specified file.

The file content will be as byte array like:

byte[] fileContent = Convert.FromBase64String(retrievedAnnotation.DocumentBody);

How do I respond to GET request with the above file content as a file?

I've stubbed out a controller:

[Route("Note({noteGuid:guid})/attachment", Name = "GetAttachment")]
[HttpGet]
public async Task<object> GetAttachment(Guid noteGuid)
{

    return new object();
}

Instead of the new object, how do I return the fileContent to the GET request?

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

1 Answers1

4

You can return file content from web api using below method

public HttpResponseMessage GetAttachment(Guid noteGuid)
{
    byte[] content = Convert.FromBase64String(retrievedAnnotation.DocumentBody);
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new ByteArrayContent(content);
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "fileName.txt";
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

    return response;
}
Mostafiz
  • 7,243
  • 3
  • 28
  • 42