用 dotnet run 命令运行一个 asp.net core 站点出现如下的错误:
Unhandled Exception: System.ArgumentException: A valid non-empty application name must be provided.
Parameter name: applicationName
at Microsoft.AspNetCore.Hosting.Internal.HostingEnvironmentExtensions.Initialize(IHostingEnvironment hostingEnvironment, String applicationName, String contentRootPath, WebHostOptions options)
at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at WebApi.Program.BuildWebHost(String[] args) in D:\dev\WebApi\Program.cs:line 18
at WebApi.Program.<Main>d__0.MoveNext() in D:\dev\WebApi\Program.cs:line 14
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at WebApi.Program.<Main>(String[] args)
Program.cs 中的代码如下:
public class Program
{
public static async Task Main(string[] args)
{
await BuildWebHost(args).RunAsync();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.Build();
}
是由于少了.UseStartup<Startup>()
,而且 Startup 中至少包含 Configure 方法
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}
}
如果不用 Startup ,可以使用 Configure(_ => {}) 避免出现这个异常
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.Configure(_ => {})
.Build();
是这样吗:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
是的