将 Web API 控制器端点添加到 Kestrel 工作程序项目

Add Web API controller endpoint to Kestrel worker project

我有一个带有 TCP 管道的 .NET Core 辅助项目,我想向其中添加一个 HTTP 控制器端点。我基本上

.

internal class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(); // not sure if I even need this
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder applicationBuilder)
    {
        applicationBuilder.UseRouting();
        applicationBuilder.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
}

.

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webHostBuilder =>
            {
                webHostBuilder.UseKestrel(kestrelServerOptions =>
                {
                    kestrelServerOptions.ListenLocalhost(5000); // this will be a config value
                }).UseStartup<Startup>();
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
}

.

[ApiController]
[Route("[controller]")]
internal class UsersController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult> Test()
    {
        return Ok();
    }
}

有人知道我错过了什么吗?

如果你想让它起作用,你需要在方法上指定默认路由

[ApiController]
[Route("[controller]")]
   public class UsersController : ControllerBase
    {
     [Route("")]
     [HttpGet]
     public async Task<ActionResult> Test()
       {
          return Ok();
       } 
    }

第二件事是制作控制器public

尝试 ConfigureKestrel 而不是 UseKestrel 配置方法

webBuilder.ConfigureKestrel(serverOptions =>
{
    serverOptions.Listen(IPAddress.Loopback, 5000);
    serverOptions.Listen(IPAddress.Loopback, 5001, 
        listenOptions =>
        {
            listenOptions.UseHttps("cert.pfx", "password");
        });
})