我正在尝试创建一个针对 netcoreapp2.0 的绝对最小的 WebHost。 我一直在引用这个但没有成功:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/hosting?tabs=aspnetcore2x
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Http;
namespace netcore_pi_project
{
class Program
{
public static void Main(string[] args)
{
BuildWebHost(args);
using (var host = WebHost.Start(router => router
.MapGet("volu", (req, res, data) =>
res.WriteAsync($"ps aux".Bash()))
.MapGet("vold", (req, res, data) =>
res.WriteAsync($"ps aux".Bash()))))
{
Console.WriteLine("Core Volume project running..");
host.WaitForShutdown();
}
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:5000")
.Build();
}
}
此构建但不会运行:
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 netcore_pi_project.Program.BuildWebHost(String[] args) in /Users/owe-macpro/projects/netcore-pi-project/Program.cs:line 31 at netcore_pi_project.Program.Main(String[] args) in /Users/owe-macpro/projects/netcore-pi-project/Program.cs:line 17
请您参考如下方法:
您问题的答案在 same page you linked 上:
Troubleshooting System.ArgumentException
Applies to ASP.NET Core 2.0 Only
If you build the host by injecting
IStartupdirectly into the dependency injection container rather than callingUseStartuporConfigure, you may encounter the following error:Unhandled Exception: System.ArgumentException: A valid non-empty application name must be provided.This occurs because the
applicationName(ApplicationKey)(the current assembly) is required to scan forHostingStartupAttributes. If you manually injectIStartupinto the dependency injection container, add the following call to yourWebHostBuilderwith the assembly name specified:
WebHost.CreateDefaultBuilder(args)
.UseSetting("applicationName", "<Assembly Name>")
...
Alternatively, add a dummy
Configureto yourWebHostBuilder, which sets theapplicationName(ApplicationKey)automatically:
WebHost.CreateDefaultBuilder(args)
.Configure(_ => { })
...
NOTE: This is only required with the ASP.NET Core 2.0 release and only when you don't call
UseStartuporConfigure.
