asp.net core 3.1 web api 配置笔记

1.创建web api项目

具体可以参考 https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio 

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.本地缓存和分布式缓存

实操步骤:

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是内存中数据存储的开源数据存储,通常用作分布式缓存。 可以在本地使用 Redis,也可以为 Azure 托管的 ASP.NET Core 应用配置Azure Redis 缓存

应用使用 Startup.ConfigureServices的非开发环境中的 RedisCache 实例(AddStackExchangeRedisCache)配置缓存实现:

C#复制

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost";
    options.InstanceName = "SampleInstance";
});

若要在本地计算机上安装 Redis:

  1. 安装Chocolatey Redis 包
  2. 在命令提示符下运行 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

7.mongodb数据库操作

todo

8.当作服务允许

window-service

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-3.1&tabs=visual-studio

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值