在运行Kestrel的ASPNETCORE控制台应用程序中未调用控制器的操作 [英] Controller's action not invoked in ASPNETCORE console app running Kestrel

查看:291
本文介绍了在运行Kestrel的ASPNETCORE控制台应用程序中未调用控制器的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个控制台应用程序运行一个接受REST调用的独立网络服务器.我的应用程序是一个内部带有ASP .NET Core的.NET Core应用程序.我在这个领域是全新的.我找到了一些示例,现在我正在努力进行控制器路由配置.使用下面的代码,使用 http://localhost:3354/api时,我总是会收到"404 Not Found"错误/Demo/Hello .有人知道我在做什么错吗?感谢您的任何建议! 我使用VS2019和ASPNETCORE 2.2.8.

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

这是DemoController类.

Here comes the DemoController class.

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

推荐答案

在对我的项目与Roman Kalinchuk的示例项目进行了调查和比较之后,我发现问题在于mvc控制器提供程序未查找控制器类型在我的应用程序组装中.将我的应用程序程序集添加到应用程序部件集合中就足够了.
参见 .AddApplicationPart(typeof(DemoController).Assembly); 行.

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

这篇关于在运行Kestrel的ASPNETCORE控制台应用程序中未调用控制器的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆