Return file in ASP.Net Core Web API
If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult
because in your current code the framework is treating HttpResponseMessage
as a model.
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}")]
public async Task<IActionResult> Download(string id) {
Stream stream = await {{__get_stream_based_on_id_here__}}
if(stream == null)
return NotFound(); // returns a NotFoundResult with Status404NotFound response.
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
Note:
The framework will dispose of the stream used in this case when the response is completed. If a
using
statement is used, the stream will be disposed before the response has been sent and result in an exception or corrupt response.
ASP.NET Minimal API How to Return/Download Files from URL
You can use Results.File
to return file to download from your Minimal APIs handler:
app.MapGet("/download", () =>
{
var mimeType = "image/png";
var path = @"path_to_png.png";
return Results.File(path, contentType: mimeType);
});
Download file from dotnet Core Web API using POST in ASP.NET MVC 5 controller
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();
How to return file from ASP.net 5 web api
used IActionResult instead of HttpResponseMessage. And returned FileStreamResult, and got it working.
Got a new problem, the file is not the one I open with the stream from server. But will create a new question for that.
Continues : Return file from ASP.NET 5 Web API
Thanks
Return file from ASP.NET 5 Web API
Please see my answer in the other post: Return file as response
For reference, I think this fits your needs:
public FileResult TestDownload()
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("YOUR PATH TO PDF"), "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
Return Download File in ASP.NET Core API from Axios Request
First of all, DownloadFile should be HttpGet instead of HttpPost.
Then your axios request should look like
axios({
url: 'http://localhost:5000/api/products/download',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
How to serve video file / stream from ASP Net Core 6 Minimal API
You can use the Results.Stream()
method to return a stream from a minimal api.
string wwwroot = builder.Environment.WebRootPath;
...
app.MapGet("/video", () =>
{
string filePath = Path.Combine(wwwroot, "test.mp4");
return Results.Stream(new FileStream(filePath, FileMode.Open));
});
The stream parameter is disposed after the response is sent.
Results.Stream
takes a few other optional parameters such as fileDownloadName
, and contentType
(which defaults to "application/octet-stream"
) that might be useful to you. Set enableRangeProcessing: true
to enable range requests.
The above could easily be adapted to take a filename
as a parameter, if you wish. You would need to consider validation (applies equally to the current code TBH). Tested and working for me.
Related Topics
How to Use a C# Keyword as a Property Name
Can't View Designer When Coding a Form in C#
Getting Image Dimensions Without Reading the Entire File
What Are the Differences Between Delegates and Events
How to Access Named Capturing Groups in a .Net Regex
How to Set an SQL Server Connection String
How to Bind a Tabcontrol to a Collection of Viewmodels
"The Remote Certificate Is Invalid According to the Validation Procedure." Using Gmail Smtp Server
What Guarantees Are There on the Run-Time Complexity (Big-O) of Linq Methods
Get Name of Property as a String
Differencebetween Debug and Release in Visual Studio
List of Timezone Ids for Use with Findtimezonebyid() in C#
Differencebetween Task.Run() and Task.Factory.Startnew()
How to Change Network Settings (Ip Address, Dns, Wins, Host Name) with Code in C#
Web App Blocked While Processing Another Web App on Sharing Same Session