How to return a file through my API configured in ASP.NET MVC 5

Asked

Viewed 150 times

1

I developed an API that searches images and now I need to deliver the files to download, so I created the following code:

public HttpResponseMessage Download(string id)
{
    Download download = new Download(id, apiUser);
    byte[] myDataBuffer = download.DownloadImage();

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(myDataBuffer);
    result.Content.Headers.ContentType =
    new MediaTypeHeaderValue("application/octet-stream");

    return result;
}

Bytes are received in the method DownloadImage(), the problem is in the HttpResponseMessage Ai ok, I put in production and through another project I have the following code:

public static void DownloadNewImage(string id)
{

    var request = new RestRequest(Method.GET);
    request.Resource = "Home/Download";
    request.AddParameter("id", id);
    RestResponse response = Execute(request, "url-do-site");
}

private static RestResponse Execute(RestRequest request, string url)
{
    var cliente = new RestClient(url);
    cliente.FollowRedirects = false;
    var response = cliente.Execute(request);          
    return (RestResponse)response;
}

When I debug Response, I get the following:

inserir a descrição da imagem aqui

Note that ContentLength = -1 and when I open the Content what was returned to me is this:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content:                    
System.Net.Http.ByteArrayContent, Headers:
{
    Content-Type: application/octet-stream
}

I believe you are returning something wrong in the method Download that returns the HttpResponseMessage, and some parameter is incorrect, someone could give me a light?

  • If using Postman and getting a get on your API in Home/Download with any valid ID works? is the image returned? Why are you using the application/octet-stream?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.