带有路由的.NET Core 2.0最小WebHost

时间:2017-10-04 22:55:46

标签: c# .net asp.net-core asp.net-core-mvc hosting

我正在尝试创建一个绝对最小的WebHost目标netcoreapp2.0。 我一直在提到这个没有成功:https://docs.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();
    }
}

这会构建但不会运行:

  

未处理的异常:System.ArgumentException:必须提供有效的非空应用程序名称。   参数名称:applicationName      在Microsoft.AspNetCore.Hosting.Internal.HostingEnvironmentExtensions.Initialize(IHostingEnvironment hostingEnvironment,String applicationName,String contentRootPath,WebHostOptions选项)      在Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)      在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

2 个答案:

答案 0 :(得分:4)

您的问题的答案在same page you linked

  

排除System.ArgumentException

的故障      

仅适用于ASP.NET Core 2.0

     

如果通过将IStartup直接注入依赖注入容器而不是调用UseStartupConfigure来构建主机,则可能会遇到以下错误:Unhandled Exception: System.ArgumentException: A valid non-empty application name must be provided.

     

这是因为applicationName(ApplicationKey)(当前程序集)需要扫描HostingStartupAttributes。如果手动将IStartup注入依赖项注入容器,请将以下调用添加到WebHostBuilder并指定程序集名称:

WebHost.CreateDefaultBuilder(args)
    .UseSetting("applicationName", "<Assembly Name>")
    ...
  

或者,在Configure添加虚假WebHostBuilder,自动设置applicationName(ApplicationKey)

WebHost.CreateDefaultBuilder(args)
    .Configure(_ => { })
    ...
  

注意:只有在您不致电UseStartupConfigure时才需要使用ASP.NET Core 2.0版本。

答案 1 :(得分:0)

在BuildWebHost中添加以下内容:

WebHost.CreateDefaultBuilder(args)
   // ... other Web Host configuration calls
   .UseSetting(WebHostDefaults.ApplicationKey, "[Application Name]")