user13755987
user13755987

Reputation:

Add Web API controller endpoint to Kestrel worker project

I have a .NET Core worker project with TCP pipelines and want to add one HTTP controller endpoint to it. I basically

.

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

Does someone know what I'm missing?

Upvotes: 3

Views: 2141

Answers (2)

svyat1s
svyat1s

Reputation: 943

Try ConfigureKestrel instead of UseKestrel configuration method

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

Upvotes: 0

Muhammad Aqib
Muhammad Aqib

Reputation: 849

You need to specify the default route on method if you want this to be work

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

And Second thing is make the controller public

Upvotes: 3

Related Questions