ASP. NET Core 2.0 WebApi Global Configuration and Log Instance

  • 2021-10-15 10:24:07
  • OfStack

Recently, the framework of ASP. Net Core 2.0 is directly used when converting the original webSerivce into WebApi. In use, the differences found with the original asp. net have been slowly solved through search and recorded for later use.

1. Global configuration

In asp. net, the global change configuration is written in web. config as follows


<?xml version="1.0"?>
<configuration>
<connectionStrings>
 <add name="conn" connectionString="Data Source=localhost;Initial Catalog=helloworld;Integrated Security=True"/>
 </connectionStrings>
 <appSettings>
 <add key="app_key" value="helloworld" />
 <add key="app_secret" value="1234567890abcdef" />
 </appSettings>
</configuration>

In ASP. Net Core 2.0 WebApi, there is no web. config file. After checking some data, you can write the global variable configuration in appsetting. json file as follows:


{
 "connectionStrings": {
 "conn": "Data Source=localhost;Initial Catalog=helloworld;Integrated Security=True"
 }
 "appSettings": {
 "app_key": "helloworld",
 "app_secret": "1234567890abcdef"
 }
}

In this way, the global variable configuration can be referenced in the program.

Using appSetting. json, global variables can be set more complex. For specific methods, please refer to the references below.

2. Log

In the past, when ASP. NET, the logs were recorded with Nlog, but now they are converted to Core 2.0, and they are ready to continue to use Nlog. In use, they are found to be different from the previous ones.

First, get the NLog. Web. AspNetCore packet in Nuget,

Then modify the code of startup. cs file


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
// Modify to 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

And in the Configure function, add the following statement:


loggerFactory.AddNLog();
app.AddNLogWeb();
loggerFactory.ConfigureNLog( " nlog.config " );

Remember to refer to using NLog. Web and using NLog. Extensions. Logging in the header;

Add 1 "Web Configuration File" with the file name nlog. config as follows:


<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <targets>
  <target xsi:type="File" name="logfile" fileName="${basedir}/logs/${shortdate}.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
  <target xsi:type="File" name="debugfile" fileName="${basedir}/logs/${shortdate}_debug.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
 <target xsi:type="File" name="errfile" fileName="${basedir}/logs/${shortdate}_error.log" keepFileOpen="false" layout="${longdate}|${callsite:fileName=True}|${uppercase:${level}}|${message} ${exception}" />
 </targets>
 <rules>
 <logger name="*" level="Debug" writeTo="debugfile" />
  <logger name="*" level="Error" writeTo="errfile" />
 <logger name="*" minlevel="Trace" writeTo="logfile" />
 </rules>
</nlog>

Then you can start calling the log function in the program.

The DEMO code for the two features is as follows:


using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using NLog.Extensions.Logging;
using NLog.Web;
public class Program
{
 public static IConfigurationRoot Configuration { get; set; }
 public static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
 public static void ConfigAndLog()
 {
  var builder = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json");
  Configuration = builder.Build();
  string app_key = Configuration["appSettings:app_key"];
  string coon = Configuration["connectionStrings:conn"];
  log.Debug(" The database connection is: " + conn);
  return;
 }
}

Related articles: