Controller's action not invoked in ASPNETCORE console app running Kestrel

Deadly 提交于 2020-07-23 07:55:26

问题


I'd like to have a console application running a standalone webserver accepting REST calls. My application is a .NET Core app with ASP .NET Core inside. I am completely new in this area. I found some examples and now I am struggling with controller route configuration. With the code below I always get "404 Not Found" error when using http://localhost:3354/api/Demo/Hello. Does anyone have an idea what am I doing wrong? Thank you for any suggestion! I use VS2019 and ASPNETCORE 2.2.8.

class Program
{
    static void Main(string[] args)
    {
        var builder = WebHost.CreateDefaultBuilder()
            .ConfigureKestrel(options => options.ListenAnyIP(3354))
            .UseStartup<Startup>();

        builder.Build().Run();
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder builder, IHostingEnvironment env)
    {
        builder.UseMvc(delegate(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute("default", "api/{controller}/{action}");
        });
    }
}

Here comes the DemoController class.

public class DemoController : Controller
{
    public IActionResult Hello()
    {
        return Ok("Hello world");
    }
}


回答1:


Your example is working fine for me on .net core 2.2 You could try explicitly declare routes like

[ApiController]
[Route("api/[controller]")]
public class DemoController : Controller
{
    [HttpGet("hello")]
    public IActionResult Hello()
    {
        return Ok("Hello world");
    }
}

Also you could consider using Visual studio built-in templates of api web applications




回答2:


After some investigation and comparison of my project with the sample project of Roman Kalinchuk I found out that the problem is that mvc controller provider doesn't look for controller types in my application assembly. It is enought to add my application assembly to the application parts collection.
See the .AddApplicationPart(typeof(DemoController).Assembly); line.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvc()
            .AddApplicationPart(typeof(DemoController).Assembly);
    }

    public void Configure(IApplicationBuilder builder, IHostingEnvironment env)
    {
        env.EnvironmentName = "Development";

        builder.UseMvc(delegate(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute("test", "api/{controller}/{action}");
        });
    }
}


来源:https://stackoverflow.com/questions/62423627/controllers-action-not-invoked-in-aspnetcore-console-app-running-kestrel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!