简体   繁体   中英

Download file from dotnet Core Web API using POST in ASP.NET MVC 5 controller

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM