【日常排雷】 .Net core 生產環境appsetting讀取失敗


關鍵詞System.ArgumentNullException: String reference not set to an instance of a String. (Parameter 's')

1.問題出現

某年某月某日,把webapi開發完了,也通過了swagger進行了單元測試。

dotnet build
dotnet publish -o publish
dotnet .\publish\xx.Webapi.dll

然后String reference not set to an instance of a String. (Parameter 's')

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.ArgumentNullException: String reference not set to an instance of a String. (Parameter 's')
   at System.Text.Encoding.GetBytes(String s)
   at AliMobilePush.Webapi.Startup.<ConfigureServices>b__5_2(JwtBearerOptions option) in E:\工作事項\code\dev-push\Alipush\AliMobilePush.Webapi\Startup.cs:line 75
   at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
   at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass11_0.<Get>b__0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.get_Value()
   at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
   at Microsoft.Extensions.Options.OptionsMonitor`1.Get(String name)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.InitializeAsync(AuthenticationScheme scheme, HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, String authenticationScheme)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

配置文件讀出來為null,為什么?

2.難道是非管理員,權限不夠?

切換至管理員,運行上述命令,還是報錯。

3.無意間解決

cd publish
dotnet xx.Webapi.dll

就能讀到了,這是為什么,根據上述命令的差異,大概能猜測到應該是路徑不同,導致讀取appsetting.json失敗。

4.原來是這樣

dotnet run,應該會根據env.ContentRootPath(env 的類型是IHostingEnvironment )來讀取配置文件 appsettings.Production.jsonappsettings.json文件,ContentRootPath 屬性得到的值為當前啟動命令的目錄,而不是dll所在的目錄,所以應在發布項目dll所在的目錄執行 dotnet xx.dll,否則會導致配置文件里面的參數讀取不到。請看源碼和命令對比:

// Host.CreateDefaultBuilder(args)

//源碼Host.cs           
builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })

5.參考鏈接

https://www.cnblogs.com/DHclly/p/9606866.html

https://www.netnr.com/home/list/115

https://github.com/dotnet/extensions.git

https://my.oschina.net/u/4364008/blog/3205437


作者:Garfield

同步更新至個人博客:http://www.randyfield.cn/

本文版權歸作者所有,未經許可禁止轉載,否則保留追究法律責任的權利,若有需要請聯系287572291@qq.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM