using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Test.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpClient("randomUserClient", client =>
{
client.BaseAddress = new Uri("https://randomuser.me/api/");
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/user", async Task<Results<BadRequest,Ok<User>,FileContentHttpResult>> (IHttpClientFactory httpClientFactory, [FromQuery] string format) =>
{
var client = httpClientFactory.CreateClient("randomUserClient");
var response = await client.GetAsync($"?format={format}");
if (!response.IsSuccessStatusCode) return TypedResults.BadRequest();
return format switch {
"json" => TypedResults.Ok(await response.Content.ReadFromJsonAsync<User>()),
"yaml" => TypedResults.File(await response.Content.ReadAsByteArrayAsync(), contentType:"text/x-yaml"),
_ => TypedResults.BadRequest()
};
});
app.Run();