Skip to content

Instantly share code, notes, and snippets.

@bradygaster
Last active June 25, 2021 01:24
Show Gist options
  • Save bradygaster/cda101df7559383a80157dc8b6f10878 to your computer and use it in GitHub Desktop.
Save bradygaster/cda101df7559383a80157dc8b6f10878 to your computer and use it in GitHub Desktop.
An OpenAPI-enabled HTTP API in .NET 5, in two files, using top-level statements programming style
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Carter;
using Carter.Response;
using Carter.OpenApi;
using Microsoft.OpenApi.Models;
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.ConfigureServices((services) =>
{
services.AddSwaggerGen(setup =>
{
setup.SwaggerDoc("Swashbuckle", new OpenApiInfo
{
Version = "v1",
Title = "Swashbuckle"
});
});
services.AddControllers();
services.AddCarter(options =>
{
options.OpenApi.DocumentTitle = "Carter";
options.OpenApi.ServerUrls = new[] { "https://localhost:5001" };
});
})
.Configure((app) =>
{
app.UseSwagger(setup =>
{
setup.RouteTemplate = "/openapi/{documentName}";
});
app.UseSwaggerUI(setup =>
{
setup.SwaggerEndpoint("/openapi/Swashbuckle", "Swashbuckle");
setup.SwaggerEndpoint("/openapi", "Carter");
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapCarter();
});
});
})
.Build()
.Run();
[Route("ServerTime")]
[ApiController]
public class TimeController : ControllerBase
{
[HttpGet]
public ActionResult<TimeResponse> GetServerTime() =>
Ok(new TimeResponse(DateTime.Now));
}
public record TimeResponse(DateTime ServerTime);
public class TimeModule : CarterModule
{
public TimeModule()
{
this.Get<GetServerTimeResponse>("/GetServerTime", async(request, response) =>
await response.AsJson(new TimeResponse(DateTime.Now)));
}
}
public class GetServerTimeResponse : RouteMetaData
{
public override string OperationId => "GetServerTime";
public override RouteMetaDataResponse[] Responses { get; } =
{
new RouteMetaDataResponse
{
Code = 200,
Description = $"A {nameof(TimeResponse)}",
Response = typeof(TimeResponse)
}
};
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>Preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Carter" Version="5.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment