KommandantKeen
KommandantKeen

Reputation: 712

ASP.NET Core console app cannot find controllers

I have created a simple .NET Core console project that includes ASP.NET core, as below:

MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
  </ItemGroup>
</Project>

And in my Program.cs:

public class Program
{
    static void Main()
    {
        WebHost.CreateDefaultBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .UseUrls("http://localhost:1234")
            .Build()
            .Run();
    }
}

In my Startup.cs I have:

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

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMvc();
    }
}

And a single controller in a Controllers folder:

public class HomeController : Controller
{
    [Route("Home/Index")]
    public IActionResult Index()
    {
        return Ok("Hello from index");
    }
}

But nothing I can do seems to make it hit my controller. The logs are showing that requests to http://localhost:1234/Home/Index are coming through Kestrel, but 404ing.

What am I missing? I have also tried specifying routes, but have had no luck in making it find the controller.

Upvotes: 5

Views: 3238

Answers (2)

Dipo
Dipo

Reputation: 132

Remove:

.UseUrls("http://localhost:1234")

That could be as a result of separate URLs in the launchSettings.json

Afterwards add the routing and endpoints to the middleware,

app.UseRouting();

app.UseEndpoints(e =>
         e.MapControllerRoute( name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}")
        
);

Also, register the mvc service

services.AddMvc();

Upvotes: 0

johnny 5
johnny 5

Reputation: 20987

I’m not sure if this is the reason why but your kestrel is using the old 1.1 version, in order for certain process to run properly such as migrations, which relies on duck typing you should declare a BuildWebHost method:

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

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

There’s more information in the docs. If this doesn’t work I would create a new project and move things across manually. The only other issue I could think of would be your package manager cache is messed up or you have too many run times installed on your machine

Upvotes: 2

Related Questions