其他分享
首页 > 其他分享> > .Net core 基础 创建及Nlog

.Net core 基础 创建及Nlog

作者:互联网

一、.Net Core 依赖注入

  1. .net core3.1 之前的版本需要手动配置swagger。当前项目.net core5.0版本自动配置完成

  2. 跨域配置

    1.下载依赖包

    2.

              //跨域
              services.AddCors(options =>
              {
                  options.AddDefaultPolicy(c =>
                  {
                      //AllowAnyOrigin 来源 AllowAnyMethod 方法 AllowAnyHeader头部信息
                      c.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();

​ }); ​ });

3.使用跨域 在路由之后 授权之前

              //路由
              app.UseRouting();
              //使用跨域!!!!
              app.UseCors();
              //授权
              app.UseAuthorization();

 

 

  1. 迁移命令:

    1.add-migration inir

    2.update-database

  2. 不使用驼峰命名规范

    services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

  3. NLog配置

    安装nlog包image-20211013103436921

    2、在项目根部创建 nlog.config(全部小写)文件。

    3、使用实例

    <?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"
        autoReload="true"
        internalLogLevel="Info"
        internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">

    <!-- enable asp.net core layout renderers -->
    <extensions>
      <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <!-- the targets to write to -->
    <targets>
      <!-- File Target for all log messages with basic details -->
      <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
              layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

      <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
      <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log"
              layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}| body: ${aspnet-request-posted-body}" />

      <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
      <target xsi:type="Console" name="lifetimeConsole" layout="${level:truncate=4:lowercase=true}: ${logger}[0]${newline}     ${message}${exception:format=tostring}" />
    </targets>

    <!-- rules to map from logger name to target -->
    <rules>
      <!--All logs, including from Microsoft-->
      <logger name="*" minlevel="Trace" writeTo="allfile" />

      <!--Output hosting lifetime messages to console target for faster startup detection -->
      <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />

      <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
      <logger name="Microsoft.*" maxlevel="Info" final="true" />
      <logger name="System.Net.Http.*" maxlevel="Info" final="true" />
       
      <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    </rules>
    </nlog>

    4、更新程序.cs 对比原代码粘贴新代码

    using NLog.Web;
    namespace ASP.NET_Core_5_NLog_Example
    {
      public class Program
      {
          public static void Main(string[] args)
          {
              var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
           
          }

          public static IHostBuilder CreateHostBuilder(string[] args) =>
              Host.CreateDefaultBuilder(args)
                  .ConfigureWebHostDefaults(webBuilder =>
                  {
                      webBuilder.UseStartup<Startup>();
                  })
                  //!!!!!!复制以下
                  .ConfigureLogging(logging =>
                  {
                      logging.ClearProviders();
                      logging.SetMinimumLevel(LogLevel.Trace);
                  })
                  .UseNLog(); // NLog: Setup NLog for Dependency injection
      }
    }

    5、配置应用程序安装. json

    {
    "Logging": {
      "LogLevel": {
      ///修改Default 为 Trace
        "Default": "Trace",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "AllowedHosts": "*"
    }

    6、 写日志 将 ILogger 注入控制器:

    using Microsoft.Extensions.Logging;

    public class HomeController : Controller
    {
      private readonly ILogger<HomeController> _logger;

      public HomeController(ILogger<HomeController> logger)
      {
          _logger = logger;

      }

      public IActionResult Index()
      {
          _logger.LogInformation("测试");
          return View();
       

     

二、EF Core

  1. .net core使用EF core如下

     

     

  2. 引用依赖包 using Microsoft.EntityFrameworkCore;

    当前类继承DBContext 创建上下文

     

     

    添加上下文

     

     

    连接数据库

     

     

  3.  

标签:core,Microsoft,跨域,public,options,NLog,Nlog,Net,logger
来源: https://www.cnblogs.com/Ji0409/p/15404194.html