在.NET Core工作项目中使用Kestrel

5
我使用Visual Studio提供的模板创建了一个新的.NET Core worker项目。我想监听传入的TCP消息和HTTP请求。我正在遵循David Fowler的“ASP.NET Core和Kestrel多协议服务器”存储库中的说明来设置Kestrel。
据我所知,我所需要做的就是安装Microsoft.AspNetCore.Hosting包以获取对UseKestrel方法的访问权限。
Program.cs文件中,我正在执行以下操作
public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
}

很遗憾,我无法将UseKestrel添加到ConfigureServices方法中。我认为这是因为我正在使用IHostBuilder接口而不是IWebHostBuilder接口。

该项目不应该是Web API项目,它应该保持为Worker项目。

有什么想法可以配置Kestrel吗?


我尝试将代码更改为示例存储库中的代码

using System.Net;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace Service
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    // ...
                })
                .UseKestrel(options =>
                {
                    // ...
                });
    }
}

当这样做时,仍然无法解决 WebHost,并出现以下错误:
  • 没有给出对“ConnectionBuilderExtensions.Run(IConnectionBuilder,Func<ConnectionContext,Task>)”的必需形式参数'middleware'相应的参数

  • 名称“WebHost”在当前上下文中不存在

我认为这是因为工作项目没有使用Web SDK。

据我所知,kestrel是webhostbuilder的扩展。如果您需要在控制台应用程序中使用Web服务器,则可以在程序.cs中使用webhostbuilder。 - Purushothaman
嗯,我尝试了一下,但是没有成功...我更新了我的问题。 - user13755987
2个回答

5

.NET 5.0如下所示

  1. Add Framework reference to ASP.NET:

    <Project Sdk="Microsoft.NET.Sdk.Worker">
        <ItemGroup>
            <FrameworkReference Include="Microsoft.AspNetCore.App" />
        </ItemGroup>
    </Project>
    
  2. Add web configuration on program.cs

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
                config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true);
    
                Configuration = config.Build();
             })
    
             //Worker
             .ConfigureServices((hostContext, services) =>
             {
                 services.AddHostedService<ServiceDemo>();
             })
    
             // web site
             .ConfigureWebHostDefaults(webBuilder =>
             {
                 webBuilder.UseStartup<Startup>();
                 webBuilder.UseKestrel(options =>
                 {
                     // HTTP 5000
                     options.ListenLocalhost(58370);
    
                     // HTTPS 5001
                     options.ListenLocalhost(44360, builder =>
                     {
                         builder.UseHttps();
                     });
                 });
             });
    
  3. Configure Startup

    public class Startup
    {
        public IConfiguration Configuration { get; }
    
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
        }
    
        public void Configure(IApplicationBuilder app)
        {
            var serverAddressesFeature = app.ServerFeatures.Get<IServerAddressesFeature>();
    
            app.UseStaticFiles();
            app.Run(async (context) =>
            {
                context.Response.ContentType = "text/html";
                await context.Response
                    .WriteAsync("<!DOCTYPE html><html lang=\"en\"><head>" +
                                "<title></title></head><body><p>Hosted by Kestrel</p>");
    
                if (serverAddressesFeature != null)
                {
                    await context.Response
                        .WriteAsync("<p>Listening on the following addresses: " +
                                    string.Join(", ", serverAddressesFeature.Addresses) +
                                    "</p>");
                }
    
                await context.Response.WriteAsync("<p>Request URL: " +
                                                  $"{context.Request.GetDisplayUrl()}<p>");
            });
        }
    }
    

5
您可以使用IHostBuilder来启用HTTP工作负载,在Host.CreateDefaultBuilder中添加.ConfigureWebHostDefaults。由于Kestrel是Web服务器,因此只能从webhost配置它。

在您的program.cs文件中:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                   webBuilder.UseStartup<Startup>();
                    webBuilder.UseKestrel(options =>
                    {
                        // TCP 8007
                        options.ListenLocalhost(8007, builder =>
                        {
                            builder.UseConnectionHandler<MyEchoConnectionHandler>();
                        });

                        // HTTP 5000
                        options.ListenLocalhost(5000);

                        // HTTPS 5001
                        options.ListenLocalhost(5001, builder =>
                        {
                            builder.UseHttps();
                        });
                    });
                });

或者

public static IHostBuilder CreateHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseKestrel(options =>
            {
                // TCP 8007
                options.ListenLocalhost(8007, builder =>
                {
                    builder.UseConnectionHandler<MyEchoConnectionHandler>();
                });

                // HTTP 5000
                options.ListenLocalhost(5000);

                // HTTPS 5001
                options.ListenLocalhost(5001, builder =>
                {
                    builder.UseHttps();
                });
            });

既然您要使用Web服务器来启用HTTP工作负载,则项目必须是Web类型。仅当项目是Web类型时,才会启用WebHost。因此,您需要更改csproj文件中的SDK,以使用Web。

<Project Sdk="Microsoft.NET.Sdk.Web">

参考资料:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接