无法在dotnet核心2.1中注册登录

ope*_*sas 2 c# asp.net logging .net-core

我创建了一个新的dotnet核心项目:

dotnet new mvc -au none -o aspnet_app
Run Code Online (Sandbox Code Playgroud)

然后按照本指南添加日志记录到应用程序

所以我将COnfigureLogging添加到Program.BuildWebHost

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostContext, logging) => 
        {
            logging.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
        })
        .UseStartup<Startup>()
        .Build();
Run Code Online (Sandbox Code Playgroud)

并且还修改了Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging();
    services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)

但是当我在HomeController中尝试使用它时:

private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) {
    _logger = logger;
}
public IActionResult Index()
{
    _logger.LogInformation("Index action!");
    return View();
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
  An unhandled exception has occurred: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'aspnet_app.Controllers.HomeController'.
Run Code Online (Sandbox Code Playgroud)

-

使用dotnet核心2.1.105

DaI*_*mTo 7

你正在编码. CreateDefaultBuilder自动构建记录器获取
hostContext.Configuration.GetSection("Logging") 你实际上不需要在program.cs或你的启动中添加antying.

只需编辑基本项目并添加它就可以了.

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

    public IActionResult Index()
    {
        _logger.LogInformation("Index action!");
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,我喜欢你给dotnet命令让我更容易测试并让它运行起来.我会记得将来这样做. (2认同)