Returning a file content from Web Api using HTTP GET request

.net, asp.net, asp.net-web-api, c#, rest

Solution

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

Problem

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?

Original source

Related problems