ASP.NET (C#) Question

Responding with a file to a get HTTP request

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

I will be creating the file like this:

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


How do I respond to GET request with the above 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?

Answer

You can do by

public FileContentResult GetAttachment(Guid noteGuid)
{

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

   FileContentResult result = new FileContentResult(content, "application/octet-stream") 
      {
         FileDownloadName = "your_file_name"
      };

   return result;
}

another alternative you can try

public ActionResult GetAttachment(Guid noteGuid)
{
    byte[] content = Convert.FromBase64String(retrievedAnnotation.DocumentBody);
    return System.Web.MVC.File(content, "text/plain", "filename.txt");
}

if you want to return from WebApi then

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