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.本地緩存和分佈式緩存

todo

7.mongodb數據庫操作

todo

 

 

發佈了137 篇原創文章 · 獲贊 29 · 訪問量 54萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章