Prepare HttpResponseMessage to return file from Web API, not getting expected results

347 views Asked by At

So, I'm stumped on something, and I have this down to the bare minimums as best I can, but complete otherwise. I'm working in C#. I have an C#.net WebAPI project AND a C#.net WPF application as the client. Its almost like the actual content of the file is never returned with the response.

On the client side, I am sending a request to a controller to get a zip file sitting on the server (my same localhost machine so I can test/debug both parts). Here is that code

private static void SamplePost()
{
    var myURL = "http://localhost:52575/MySvc/GetZipFromWebAPI";
    var request = WebRequest.Create(myURL);
    request.Method = "POST";
    var data = System.Text.Encoding.ASCII.GetBytes("test string");
    request.Method = "POST";
    request.ContentType = "text/plain";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
}

Now, on the WebAPI project, I have the controller and public method that does nothing but try to return a fixed-known zip file.

public HttpResponseMessage GetZipFromWebAPI()
{
    var fileToSendBack = @"C:\Users\Public\Sample.zip";
    var fileBytes = System.IO.File.ReadAllBytes(fileToSendBack);
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    var oneContent = new ByteArrayContent(fileBytes);
    oneContent.ReadAsByteArrayAsync();
    response.Content = oneContent;
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    return response;
}

So, I try as simple as send the request, and return a response. Upon the many different attempts I have sampled with, the best I had on the return was that the file size was correct (about 12k zip file), but no ZIP on the client side when I get the response.

Whatever parts I am missing / mis-understanding would be great to have resolved. I have gone through many posts that showed one side or the other, but even working with those, not getting what I think SHOULD be simple.

1

There are 1 answers

4
Abir Stolov On

One thing that is missing on the Web-API side is the Method and Parameter Attributes Something like

[HttpPost]
public HttpResponseMessage GetZipFromWebAPI([FromBody] string data)