flower-story/Server/Controller/SwaggerController.cs

140 lines
3.8 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Text;
namespace Blahblah.FlowerStory.Server.Controller;
/// <inheritdoc/>
[Route("apidoc")]
public class SwaggerController : ControllerBase
{
private readonly SwaggerGenerator generator;
/// <inheritdoc/>
public SwaggerController(SwaggerGenerator generator)
{
this.generator = generator;
}
/// <inheritdoc/>
[Route("get/{version}")]
[HttpGet]
public ActionResult GetApi(string version)
{
var model = generator.GetSwagger(version);
var builder = new StringBuilder();
builder.Append($@"<!DOCTYPE html>
<html lang=""zh-cn"">
<head>
<meta charset=""UTF-8"">
<title>Flower Story - API 接口文档</title>
<style type=""text/css"">
table,
table td,
table th {{
margin: 0;
padding: 0;
border: 1px solid #000;
border-collapse: collapse;
}}
table {{
table-layout: fixed;
word-break: break-all;
}}
tr {{
height: 20px;
font-size: 12px;
}}
.wrapper {{
width: 1000px;
margin: 0 auto;
}}
.operation {{
width: 100%;
}}
.bg {{
background-color: rgb(84, 127, 177);
}}
</style>
</head>
<body>
<div class=""wrapper"">
<h1>{model.Info.Title}</h1>
<h3>接口文档 {model.Info.Version}</h3>
<p>{model.Info.Description}</p>");
foreach (var item in model.Paths)
{
if (item.Value.Operations != null)
{
foreach (var operation in item.Value.Operations)
{
if (string.IsNullOrEmpty(operation.Value.Summary))
{
continue;
}
builder.Append($@"
<h3>{operation.Value.Summary}</h3>
<table class=""operation"">
<tr class=""bg""><td colspan=""5""></td></tr>
<tr>
<td>URL</td>
<td colspan=""4"">{item.Key}</td>
</tr>
<tr>
<td>请求方式</td>
<td colspan=""4"">{operation.Key}</td>
</tr>");
if (operation.Value.Parameters?.Count > 0)
{
builder.Append(@"
<tr class=""bg"">
<td>参数</td>
<td>参数类型</td>
<td>是否必须</td>
<td colspan=""2"">说明</td>
</tr>");
foreach (var param in operation.Value.Parameters)
{
builder.Append($@"
<tr>
<td>{param.Name}</td>
<td>{param.In}</td>
<td>{param.Required}</td>
<td colspan=""2"">{param.Description}</td>
</tr>");
}
}
if (operation.Value.Responses?.Count > 0)
{
builder.Append(@"
<tr class=""bg"">
<td>状态码</td>
<td colspan=""4"">说明</td>
</tr>");
foreach (var response in operation.Value.Responses)
{
builder.Append($@"
<tr>
<td>{response.Key}</td>
<td colspan=""4"">{response.Value.Description}</td>
</tr>");
}
}
builder.Append(@"
</table>");
}
}
}
builder.Append(@"
</div>
</body>
</html>");
return Content(builder.ToString(), "text/html");
}
}