【问题标题】:ArgumentNullException for ConnectionString When trying to remotely connect to .net core API尝试远程连接到 .net 核心 API 时 ConnectionString 的 ArgumentNullException
【发布时间】:2019-01-27 22:54:58
【问题描述】:

首先这是在 Mac 上发生的,我是 dotnet core 的新手。

我已经安装了 docker 并在 dotnet core 中设置了所有内容。我确实将连接字符串添加到 'appsettings' 和 'appsettings(Development)'。

"ConnectionStrings": {
    "Default": "server=localhost; database=Monitor; User ID=sa; Password=MyComplexpPassword!234;"
  },

这是 Program.cs 文件的主要方法

 public static void Main(string[] args)
 {
      CreateWebHostBuilder(args).Build().Run();
 }

这是 startup.cs 类的 ConfigureServices 方法。

public void ConfigureServices(IServiceCollection services)
{
      services.AddAutoMapper();

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

      services.AddDbContext<MonitorDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

            // In production, the Angular files will be served from this directory
      services.AddSpaStaticFiles(configuration =>
      {
           configuration.RootPath = "ClientApp/dist";
      });

      services.AddScoped<IUserRepository,UserRepository>();
 }

这是一个Controller测试方法来测试API。

[HttpGet("getUser")]
public UserResource GetUserInfo()
{
       var user_1 = new User();

       user_1.FirstName = "MAC";
       user_1.LastName = "OS TEST";
       user_1.Username = "Apple@gmail.com";


       return mapper.Map<User, UserResource>(user_1);
}

如果我在没有设置远程访问的 Program.cs 类的情况下进行休息调用(http),此方法将完美执行。

现在我已将它设置为在“http://0.0.0.0:6001”中运行,这样我就可以从我的手机或同一 wifi 中的另一台电脑访问 API。 我关注了This instructions

现在我的 Program.cs 的 main 方法是这样的。

public static void Main(string[] args)
{
       // CreateWebHostBuilder(args).Build().Run();

       var configuration = new ConfigurationBuilder()
                .AddCommandLine(args)
                .Build();


       var hostUrl = configuration["hosturl"];
            if (string.IsNullOrEmpty(hostUrl))
                hostUrl = "http://0.0.0.0:6000";


       var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls(hostUrl)   // <!-- this 
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseConfiguration(configuration)
                .Build();

            host.Run();

}

在终端中我运行了这个命令dotnet run --hosturl http://0.0.0.0:6001

如果尝试访问与发生这种情况之前相同的方法。

注意:- 我只更改了主机,因为我需要用其他设备测试 API。

我有其他控制器和方法正在连接到数据库并对其进行粗略操作,这些 API 调用也面临同样的问题。仅当我将其设置为远程访问时才会发生这种情况。

注意:- 如果我像这样更改 Startup.cs 类连接字符串行,它将在两种配置中完美运行。

services.AddDbContext<MonitorDbContext>(options => options.UseSqlServer("server=localhost; database=Monitor; User ID=sa; Password=MyComplexpPassword!234;"));

但我觉得这不是一个好习惯。将来,我必须将 JWT Authentication 添加到 API,以便 APP_Secret 也需要添加到 AppSettings.json 文件中。

谢谢。

【问题讨论】:

  • 如果您添加配置的唯一位置是命令行,而您的配置存储在命令行中,您希望它如何工作?您是否查看过文档以了解如何从文件中添加配置?
  • @mason 你能解释一下,我应该配置什么?
  • 你看到你在哪里设置你的配置了吗?它说 AddCommandLine,对吧?但是您没有在命令行上传递连接字符串,是吗?你在配置文件中有它,但你还没有告诉它从配置文件中读取配置。该文档解释了它是如何工作的。 docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/…
  • @mason 我认为 Startup 中的配置和 Program 中的配置不是同一个配置。

标签: c# .net-core


【解决方案1】:

您没有告诉应用程序使用appsettings.json。更改以下配置

var configuration = new ConfigurationBuilder()
    .AddCommandLine(args)
    .Build();

var configuration = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddCommandLine(args)
    .Build();

【讨论】:

  • 感谢您的建议。它需要一些改变,它是问题的解决方案。
【解决方案2】:

作为替代方案,您可以使用静态WebHost.CreateDefaultBuilder 方法,该方法默认从“appsettings.json”、“appsettings.[EnvironmentName].json”、命令行参数加载设置。

注意 -> 如here 所述:

AddCommandLine 已被CreateDefaultBuilder 调用。如果你 需要提供应用程序配置并且仍然能够覆盖它 使用命令行参数配置,调用应用程序的附加 ConfigureAppConfiguration 中的提供者并最后调用 AddCommandLine

WebHost.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        // Call other providers here and call AddCommandLine last.
        config.AddCommandLine(args);
    })
    .UseStartup<Startup>();

【讨论】:

    猜你喜欢
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多