Hi @mc
You can use FileStreamResult
to show pdf file, it will not start download.
You can change your code like below, and create a wwwroot
folder in your project.
Program.cs
namespace SwaggerApi
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Add this line for show pdf
builder.Services.AddHttpClient("PdfDomain", client => {
client.BaseAddress = new Uri("https://localhost:7055/");
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
// add this for access static files under wwwroot folder
app.UseStaticFiles();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
PdfController.cs
using Microsoft.AspNetCore.Mvc;
namespace SwaggerApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public PdfController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
[Route("external-domain-pdf")]
public async Task<IActionResult> ExternlDomainPdf()
{
string url = "/images/sample.pdf";
var httpClient = _httpClientFactory.CreateClient("PdfDomain");
var response = await httpClient.GetAsync(url);
MemoryStream ms = new MemoryStream(await response.Content.ReadAsByteArrayAsync());
return new FileStreamResult(ms, "application/pdf");
}
}
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Jason