具体可以参考 https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio
NSwag 提供了下列功能:
C#复制
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(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();
}
若要安装 NSwag NuGet 包,请使用以下方法之一:
从“程序包管理器控制台”窗口:
转到“视图” > “其他窗口” > “程序包管理器控制台”
导航到包含 TodoApi.csproj 文件的目录
请执行以下命令:
PowerShell复制
Install-Package NSwag.AspNetCore
下步骤,在 ASP.NET Core 应用中添加和配置 Swagger:
Startup.ConfigureServices
方法中,注册所需的 Swagger 服务:Startup.Configure
方法中,启用中间件为生成的 Swagger 规范和 Swagger UI 提供服务:http://localhost:/swagger
,以查看 Swagger UI。http://localhost:/swagger/v1/swagger.json
,以查看 Swagger 规范。安装组件
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;
}
}
app.UseExceptionHandler("/error");
[Route("/error")]
public IActionResult Error()
{
var context = HttpContext.Features.Get();
Console.WriteLine("context.Error.StackTrace:" + context.Error.StackTrace);
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message,
statusCode: 500);
}
可以在error中设置发送邮件,记录日志,设置返回状态等 。
使用 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();
}
实操步骤:
1.添加引用:
Microsoft.Extensions.Caching.StackExchangeRedis
2.修改配置文件
"RedisDBSettings": {
"ConnectionString": "127.0.0.1:6379,connectTimeout=500,ssl=False,abortConnect=False",
"DatabaseName": "1",//db的id
"InstanceName": "SBCC_Survey_" //默认实例名称作为key的前缀,线上不需要修改
}
3.startup增加扩展方法,读取配置,注入(实现是StackExchangeRedis)
//redis
#region snippet_AddStackExchangeRedisCache
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = Configuration["RedisDBSettings:ConnectionString"];
options.InstanceName = Configuration["RedisDBSettings:InstanceName"];
});
#endregion
然后直接 获取即可。
private IDistributedCache _cache;(默认支持二进制,可以扩展方法进行二进制转换,支持泛型)
可以参考 https://www.cnblogs.com/OpenCoder/p/10287743.html
Redis是内存中数据存储的开源数据存储,通常用作分布式缓存。 可以在本地使用 Redis,也可以为 Azure 托管的 ASP.NET Core 应用配置Azure Redis 缓存。
应用使用 Startup.ConfigureServices
的非开发环境中的 RedisCache 实例(AddStackExchangeRedisCache)配置缓存实现:
C#复制
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});
若要在本地计算机上安装 Redis:
redis-server
官方文档介绍:
https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed?view=aspnetcore-3.1
官方demo:https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/performance/caching/distributed/samples/3.x/DistCacheSample
todo