[英]Running .NET Core 2.0 API from the command line
當我在 Visual Studio 2017 中運行使用 HttpSys 的 .NET Core 2.0 編寫的 REST API 時,我得到以下輸出:
exe 路徑:C:\\Program Files\\dotnet\\dotnet.exe 目錄:C:\\Program Files\\dotnet 連接字符串:Server=(localdb)\\mssqllocaldb;Database=MyApp;Trusted_Connection=True;MultipleActiveResultSets=true 托管環境:開發內容根路徑:C:\\Users\\Torsten\\source\\repos\\MyApp\\MyApp 現在正在監聽:http://*:5000 應用程序啟動。 按 Ctrl+C 關閉。
當我從命令行運行相同的應用程序時
dotnet myapp
我得到這個輸出:
dotnet MyApp.dll Exe 路徑:C:\\Program Files\\dotnet\\dotnet.exe 目錄:C:\\Program Files\\dotnet 連接字符串:信息:Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0] 用戶配置文件可用。 使用“C:\\Users\\Torsten\\AppData\\Local\\ASP.NET\\DataProtection-Keys”作為密鑰存儲庫和 Windows DPAPI 來加密靜態密鑰。 System.ArgumentNullException:值不能為空。 參數名稱:connectionString
為什么從命令行啟動時無法識別連接字符串?
連接字符串在 appsettings.json 中定義為:
{
"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyApp;Trusted_Connection=True;MultipleActiveResultSets=true" },
Startup.cs 顯示:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
Console.WriteLine("Exe path : " + pathToExe);
Console.WriteLine("Directory : " + Path.GetDirectoryName(pathToExe));
Console.WriteLine("Command line arguments :" + String.Join(", ",Environment.GetCommandLineArgs()));
Console.WriteLine("Connection string : " + Configuration["ConnectionStrings:DefaultConnection"]);
services.AddDbContext<MyAppContext>(options =>
options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
services.AddMvc();
}
無法讀取 ConnectionString 的原因是,默認情況下 appsettings.json 不會復制到輸出目錄。 只有當您將Copy to Output Directory配置為Copy if newer或Copy always 時,它才會被復制到輸出目錄。 您可以通過查看Configure
方法中的env.ContentRootPath
。
從 Visual Studio 中啟動時,ContentRootPath 是項目目錄。
C:\\Users\\Somebody\\source\\repos\\MyApp\\MyApp
從命令行啟動時,ContentRootPath 是輸出目錄。
C:\\Users\\Somebody\\source\\repos\\MyApp\\MyApp\\bin\\debug\\netcoreapp2.0
從項目文件夾重新運行帶有 -v 開關的 dotnet 命令以查看結果。 如果您看到對 . ..\\microsoft.entityframeworkcore.tools.dotnet\\1.0.0..問題在於必須更新的 CLIToolReference。
當我從舊版本的 asp.net core 遷移項目時,我遇到了同樣的問題。 遷移后,DotNetCliToolReference 不會自動更新。 更新yourproject.csproj文件以使用2.0.0版本的 CLI,如以下代碼段所示:
<ItemGroup>
...
<DotNetCliToolReference
Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version="2.0.0" />
</ItemGroup>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.