让.NET9中的OpenAPI有脸面

文摘   2024-05-29 09:28   日本  

前一篇简单说了一下怎么在项目中引入新的OpenAPI,本篇再进一步,看看怎么引入UI界面。

主要做法是通过添加/scalar/openapidemo这个静态页面实现,在页面中,引入了scalar的js,关于scalar,请详看https://scalar.com。其他信息与上一篇介绍的差不多。代码如下:

using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging.Configuration;using Microsoft.OpenApi.Extensions;using Microsoft.OpenApi.Interfaces;using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi("openapidemo", opt =>{ opt.UseTransformer((openApiDoc, context, c) => {
openApiDoc.Info = new OpenApiInfo { Version = "v1.1.1", Title = "测试API", Description = "本项是测试.NET自带的OpenAPI。" }; return Task.CompletedTask; }); opt.UseOperationTransformer((o, c, c1) => { Console.WriteLine("DocumentName:" + opt.DocumentName); return Task.CompletedTask; });});var app = builder.Build();app.MapOpenApi();app.MapGet("/scalar/{documentName}", (string documentName) => Results.Content($$""" <!doctype html> <html> <head> <title>Scalar API Reference -- {{documentName}}</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <script id="api-reference" data-url="/openapi/{{documentName}}.json"></script> <script> var configuration = { theme: 'purple', } document.getElementById('api-reference').dataset.configuration = JSON.stringify(configuration)</script> <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script> </body> </html> """, "text/html")).ExcludeFromDescription();app.MapGet("/order", () =>{ return new Order() { OrderNo = "20210901", Amount = 100, OrderDate = DateTime.Now };});app.MapPost("/order", (Order order) =>{ return new OkResult();});app.Run();
/// <summary>/// 订单/// </summary>public class Order{ /// <summary> /// 订单编号 /// </summary> public string OrderNo { get; set; } /// <summary> /// 订单金额 /// </summary> public decimal Amount { get; set; } /// <summary> /// 订单日期 /// </summary> public DateTime OrderDate { get; set; }
}

这时,通过访问http://localhost:5287/scalar/openapidemo,就可以查看可视见的API信息了,主界面如下:

order的get请求:

order的post请求:

order的post方法的Test Request:

使用Scalar最大好处是它内置了很多咱语言的调用api的方式,这样可以方便不同的对接人,复制粘贴,拿走不谢,简单快捷。

桂迹
分享原创,记录痕迹!
 最新文章