Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding AspNet Core to standard Dotnet Core Console app

I have an existing Dotnet Core 2.0 Console application that is a long running app (until user quits it).

I want to add a Rest API to this and wanted to add AspNet Core MVC to do this, however all I get back is a 404 when I visit http://localhost:5006/api/values Kestrel is working and picking up the request but it isn't making it to my controller!

I've added NuGet packages to Microsoft.AspNetCore, Microsoft.AspNetCore.Mvc. I also added a reference to Microsoft.AspNetCore.All but this didn't work either so I have now removed it as I don't need all the bloat.

I call this in my applications static Main()

private static void StartWeb()
{
    var host = WebHost
              .CreateDefaultBuilder()
              .UseKestrel()
              .UseStartup<WebStartup>()
              .UseUrls("http://*:5006")
              .Build();
    host.Start();
}

And this is the WebStartup class

namespace myApp
{
    public class WebStartup
    {
        public IConfiguration Configuration { get; }
        public WebStartup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

        }
    }
}

Finally in a Controllers folder I have a class called ValuesControler

namespace myApp.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    class ValuesController : Controller
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}
like image 413
Matt Avatar asked Oct 19 '25 12:10

Matt


1 Answers

In order for ASP.NET Core MVC to recognise your Controller classes, they must be declared public. In your example, you have not specified that ValuesController is a public class - instead it defaults to internal, which is why it is not being picked up and results in a 404:

public class ValuesController : Controller
like image 105
Kirk Larkin Avatar answered Oct 22 '25 03:10

Kirk Larkin