1.创建web api项目
2. 增加 接口描述文档
NSwag 提供了下列功能:
C#复制
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddMvc();
// Register the Swagger services
services.AddSwaggerDocument();
}
C#复制
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
// Register the Swagger generator and the Swagger UI middlewares
app.UseOpenApi();
app.UseSwaggerUi3();
app.UseMvc();
}
- 能够使用 Swagger UI 和 Swagger 生成器。
- 灵活的代码生成功能。
-
若要安装 NSwag NuGet 包,请使用以下方法之一:
-
从“程序包管理器控制台”窗口:
-
转到“视图” > “其他窗口” > “程序包管理器控制台”
-
导航到包含 TodoApi.csproj 文件的目录
-
请执行以下命令:
PowerShell复制
Install-Package NSwag.AspNetCore
-
-
下步骤,在 ASP.NET Core 应用中添加和配置 Swagger:
- 在
Startup.ConfigureServices
方法中,注册所需的 Swagger 服务: - 在
Startup.Configure
方法中,启用中间件为生成的 Swagger 规范和 Swagger UI 提供服务: - 启动应用。 转到:
http://localhost:<port>/swagger
,以查看 Swagger UI。http://localhost:<port>/swagger/v1/swagger.json
,以查看 Swagger 规范。
3.支持自定义的json格式刷程序
安装组件
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.1
services.AddControllers()
.AddNewtonsoftJson(opt =>
{//小驼峰序列化
opt.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
// Configure a custom converter
opt.SerializerSettings.Converters.Add(SerializerHelper.JsonTimeConverter());
});
public class SerializerHelper
{
public static JsonConverter JsonTimeConverter()
{
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter
{
DateTimeFormat = "yyyy'-'MM'-'dd HH:mm:ss"
};
return timeConverter;
}
}
4.处理异常
app.UseExceptionHandler("/error");
[Route("/error")]
public IActionResult Error()
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
Console.WriteLine("context.Error.StackTrace:" + context.Error.StackTrace);
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message,
statusCode: 500);
}
可以在error中设置发送邮件,记录日志,设置返回状态等 。
5.日志
使用 nlog https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3
需要注意的是,如果是单exe,需要设置根目录,还有log路径,如果设置相对路径,需要设置"${basedir:processDir=true}参数。
var rootPath = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
#if DEBUG
rootPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
#endif
var logger = NLogBuilder.ConfigureNLog(Path.Combine(rootPath, "nlog.config")).GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
<!-- write logs to file -->
<target xsi:type="File" concurrentWrites="true"
name="allFile"
fileName="${basedir:processDir=true}/logs/all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
6.本地缓存和分布式缓存
todo
7.mongodb数据库操作
todo