3
votes

I need to download a file from dotnet Core Web API. The controller accepts POST requests and looks like this:

    [HttpPost]
    [Route("api/pdf")]
    //[Consumes("application/octet-stream")]
    [Produces("application/pdf")]
    public IActionResult GetPDF([FromBody] ReportRequest request)
    {
       //report generation logic
       return new FileStreamResult(pdfMemoryStream, "application/pdf");
    }

I'm not sure how to send a POST request from a ASP.NET MVC 5 controller to this dotnet core API controller

I've tried WebClient.UploadData(action, "POST", requestBytes); where requestBytes is a byte array of the model obtained using BinaryFormatter, but the API controller rejects it saying (406) Not Acceptable.

This happens regardless of [Consumes("application/octet-stream")] on the API controller.

And there is no overload of WebClient.UploadData that allows POSTing JSON.

Any example would be greatly appreciated.

1

1 Answers

2
votes

Change GetPdf method to:

[Consumes("application/json")]
public IActionResult GetPDF([FromBody] ReportRequest request)
{
    //report generation logic
    return File(pdfMemoryStream.ToArray(), "application/pdf");
}

and use HttpClient instead of WebClient:

var client = new HttpClient();
string url = "https://localhost:44398/api/values/GetPdf";
var reportRequest = new ReportRequest()
{
    Id = 1,
    Type = "Billing"
};
var json = JsonConvert.SerializeObject(reportRequest);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, data);
response.EnsureSuccessStatusCode();
var bytes = await response.Content.ReadAsByteArrayAsync();