I have a .NET Core worker project and want to add a library providing several HTTP endpoints. I have to stay with the worker project, I can't change it to a Web API project. What I have done so far:
- I created a worker project
- I created a library project
- I added a reference to the library in the worker project
- In the Worker.csproj and Lib.csproj I added
<FrameworkReference Include="Microsoft.AspNetCore.App" />to the item group to gain access to the webbuilder stuff - I installed the package Microsoft.AspNetCore.Mvc.Core in the library project
- In the library project I add several extensions classes and a web API controller for testing purposes
.
public static class IApplicationBuilderExtensions
{
public static IApplicationBuilder AddLibrary(this IApplicationBuilder applicationBuilder)
{
applicationBuilder.UseRouting();
applicationBuilder.UseEndpoints(endpoints => { endpoints.MapControllers(); });
return applicationBuilder;
}
}
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddLibrary(this IServiceCollection services)
{
services.AddMvc(); // this might be not needed
services.AddControllers();
return services;
}
}
public static class KestrelServerOptionsExtensions
{
public static void AddLibrary(this KestrelServerOptions kestrelServerOptions)
{
kestrelServerOptions.ListenLocalhost(5000); // value from config
}
}
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public async Task<ActionResult> Test()
{
return Ok();
}
}
- In the worker project I created a
Startupclass
.
internal class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddLibrary();
}
public void Configure(IApplicationBuilder applicationBuilder)
{
applicationBuilder.AddLibrary();
}
}
- In the worker project I modified the
Programclass to
.
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.AddLibrary();
}).UseStartup<Startup>();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
- I run the project and call GET http://localhost:5000/users
- I would expect a 200 but get a 404 and the debugger does not hit the controller endpoint in the library project
Does someone know what I'm missing?
It is possible for me to Add Web API controller endpoint to Kestrel worker project but it is not possible for me to add web controllers to a library project and call them from the library.

[Route("[controller]")]to[Route("[controller]/[action]")]. I hope this would resolve the error. Thanks,