add NSwag documentation

This commit is contained in:
YuukanOO 2020-12-18 14:50:07 +01:00
parent b5c6292230
commit 6528f83028
7 changed files with 144 additions and 1 deletions

View File

@ -1,7 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NSwag.AspNetCore" Version="13.9.4" />
</ItemGroup>
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net5.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@ -0,0 +1,44 @@
using System.Threading.Tasks;
using HN.Application;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public sealed class LinksController : ControllerBase
{
private readonly IMediator _bus;
public LinksController(IMediator bus)
{
_bus = bus;
}
/// <summary>
/// Retrieve all links already posted.
/// </summary>
/// <returns></returns>
[ProducesResponseType(typeof(LinkDto[]), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetLinks()
{
return Ok(await _bus.Send(new ListLinksQuery()));
}
/// <summary>
/// Post a new link.
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> CreateLink(AddLinkCommand command)
{
var result = await _bus.Send(command);
return Created("blabla", result);
}
}
}

View File

@ -0,0 +1,32 @@
using System;
using HN.Application;
using HN.Infrastructure.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
namespace Api
{
public sealed class HttpExecutingUserProvider : IExecutingUserProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly UserManager<User> _userManager;
public HttpExecutingUserProvider(IHttpContextAccessor httpContextAccessor, UserManager<User> userManager)
{
_httpContextAccessor = httpContextAccessor;
_userManager = userManager;
}
public Guid GetCurrentUserId()
{
var uid = _userManager.GetUserId(_httpContextAccessor.HttpContext.User);
if (!Guid.TryParse(uid, out Guid result))
{
throw new UserNotConnected();
}
return result;
}
}
}

View File

@ -1,12 +1,24 @@
using System;
using HN.Application;
using HN.Infrastructure;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
namespace Api namespace Api
{ {
public class MockExecutingContext : IExecutingUserProvider
{
public Guid GetCurrentUserId()
{
return Guid.NewGuid();
}
}
public class Startup public class Startup
{ {
public Startup(IConfiguration configuration) public Startup(IConfiguration configuration)
@ -20,21 +32,43 @@ namespace Api
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddHN(Configuration).ResolveConnectedUserWith<MockExecutingContext>();
services.AddHttpContextAccessor();
// Permet d'avoir des routes en lowercase
services.Configure<RouteOptions>(options =>
{
options.LowercaseUrls = true;
options.LowercaseQueryStrings = true;
});
services.AddControllers();
services.AddSwaggerDocument(d =>
{
d.PostProcess = od =>
{
od.Info.Title = "Hacker news like API in .Net";
};
d.SchemaType = NJsonSchema.SchemaType.OpenApi3;
});
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ {
app.UseOpenApi();
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseSwaggerUi3();
} }
app.UseRouting(); app.UseRouting();
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapControllers();
endpoints.MapGet("/", async context => endpoints.MapGet("/", async context =>
{ {
await context.Response.WriteAsync("Hello World!"); await context.Response.WriteAsync("Hello World!");

View File

@ -0,0 +1,12 @@
using System;
namespace Api
{
public sealed class UserNotConnected : Exception
{
public UserNotConnected() : base("User not connected!")
{
}
}
}

View File

@ -6,5 +6,8 @@
"Microsoft.Hosting.Lifetime": "Information" "Microsoft.Hosting.Lifetime": "Information"
} }
}, },
"ConnectionStrings": {
"Default": "Data Source=../Website/hn.db"
},
"AllowedHosts": "*" "AllowedHosts": "*"
} }

View File

@ -167,13 +167,17 @@ $ cd Api
$ dotnet new gitignore $ dotnet new gitignore
``` ```
L'attribut ApiController : https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0#apicontroller-attribute
On ajoute NSwag pour la génération de la documentation avec `dotnet add package NSwag.AspNetCore`.
Pour plus tard, pour la génération de doc : Pour plus tard, pour la génération de doc :
project.csproj project.csproj
<PropertyGroup> <PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>bin\YourApi.XML</DocumentationFile> <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup> </PropertyGroup>
## Docker ## Docker