I have some PDFs stored in my dropbox location and want users to be able to retrieve them via a call to an API.
[HttpGet("{key}")]
public async Task<ActionResult> GetPDF(string key) {
string? path = GetPath(key);
if (path == null) {
return NotFound();
}
using(System.Net.Http.HttpClient wc = new System.Net.Http.HttpClient()) {
try {
using(System.IO.Stream stream = await wc.GetStreamAsync(path)) {
// using(System.IO.Stream stream = wc.GetStreamAsync(path).GetAwaiter().GetResult()) {
return new FileStreamResult(stream, "application/pdf");
}
} catch(System.Exception ex) {
return NotFound();
}
}
}
It runs right through, without hitting the exception, and returns, then gives the error
The ReadAsync method cannot be called when another read operation is pending.
Waiting for the async method didn't help.
CodePudding user response:
Your primary issue appears to be that the stream has been disposed before the function returns. FileStreamResult
will dispose the stream, you don't need to do that.
Also, HttpClient
should be a global field, otherwise you could get socket exhaustion issues.
HttpClient wc = new HttpClient();
[HttpGet("{key}")]
public async Task<ActionResult> GetPDF(string key)
{
string? path = GetPath(key);
if (path == null)
{
return NotFound();
}
try
{
var stream = await wc.GetStreamAsync(path);
return new FileStreamResult(stream, "application/pdf");
}
catch(System.Exception ex)
{
return NotFound();
}
}