How to return a file (FileContentResult) in ASP.NET WebAPI
Instead of returning StreamContent
as the Content
, I can make it work with ByteArrayContent
.
[HttpGet]
public HttpResponseMessage Generate()
{
var stream = new MemoryStream();
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
How to return a file in ASP.NET WebAPI
You can (should?) use ActionResults to return data from your API.
[HttpGet]
[Route("GetReport")]
public ActionResult GetReport()
{
return File(System.IO.File.OpenRead(PDF_TEMP_PATH), "application/pdf");
}
You'll just have to set your ContentType
accordingly.
Another good practice is to make your method async to a void blocking.
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.
Returning binary file from controller in ASP.NET Web API
Try using a simple HttpResponseMessage
with its Content
property set to a StreamContent
:
// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;
public HttpResponseMessage Post(string version, string environment,
string filetype)
{
var path = @"C:\Temp\test.exe";
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
A few things to note about the stream
used:
You must not call
stream.Dispose()
, since Web API still needs to be able to access it when it processes the controller method'sresult
to send data back to the client. Therefore, do not use ausing (var stream = …)
block. Web API will dispose the stream for you.Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a
MemoryStream
), make sure tostream.Seek(0, SeekOrigin.Begin);
or setstream.Position = 0;
With file streams, explicitly specifying
FileAccess.Read
permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.
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;
}
Download and return a file from asp.net webapi
Just removing the using
didn't seem to fix my problem. I've re-written it a bit, and this seems to have fixed my problem.
[HttpGet]
[AllowAnonymous]
[Route(template: "Reward/FooLogo/{fooId}/bar/{barId}", Name = "FooLogo")]
public async Task<HttpResponseMessage> FooLogo(int fooId, int barId)
{
var foo = await GetFooAsync(fooId, barId);
if (string.IsNullOrWhiteSpace(foo?.ImageUrl))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
using (var client = new HttpClient())
{
var res = await client.GetAsync(paymentMethod.ImageUrl);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(await res.Content.ReadAsStreamAsync());
response.Content.Headers.ContentType = res.Content.Headers.ContentType;
return response;
}
}
Related Topics
Sorting String Values Without Using Any Method/Function
How to Convert String Formula to a Mathematical Formula in C#
Add Header and Footer for Pdf Using Itextsharp
Searching If Value Exists in a List of Objects Using Linq
Using Selenium2, How to Check If Certain Text Exists on the Page
Formatting Date in Linq-To-Entities Query Causes Exception
How Avoid Adding Duplicates to Database Managed by Entityframework Caused by Seed Method
C# Lamba With Datetime and Between
C# Find Highest Array Value and Index
How to Get Url Referrer in ASP.NET Core MVC
How to Convert Word Files to Pdf Programmatically
Fast Way of Finding Most and Least Significant Bit Set in a 64-Bit Integer
String Array to Int Array Conversion
Httpcontext.Current.Request.Files Is Always Empty
Notify When Thread Is Complete, Without Locking Calling Thread
How to Get Name by String Value from a .Net Resource (Resx) File