微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在.NET Core Worker项目中使用Kestrel

如何解决在.NET Core Worker项目中使用Kestrel

我使用Visual Studio提供的模板创建了一个新的.NET Core worker项目。我想监听传入的TCP消息和HTTP请求。我正在关注David Fowler's "Multi-protocol Server with ASP.NET Core and Kestrel" repository,如何设置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 )”的所需形式参数“中间件”相对应的参数。

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

我认为发生这种情况是因为工作人员项目没有使用Web SDK。

解决方法

使用IHostbuilder启用HTTP工作负载,需要在.ConfigureWebHostDefaults中添加Host.CreateDefaultBuilder。由于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。因此,您需要更改SDK才能在csproj文件中使用Web。

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

参考:

,

NET 5.0 如下

1 添加对 ASP.NET 的框架引用:

<Project Sdk="Microsoft.NET.Sdk.Worker">
      <ItemGroup>
         <FrameworkReference Include="Microsoft.AspNetCore.App" />
      </ItemGroup>
 </Project>

2:在program.cs上添加web配置

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:配置启动

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>");
            });
            
        }
     
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。