Home > other >  asp.net core none of the controllers are initialized
asp.net core none of the controllers are initialized

Time:08-03

I have an ASP.NET project and everything is returning a 404, here's my startup code

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();
        else
            app.UseExceptionHandler("/Home/Error");

        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseRouting();

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

            endpoints.MapGet("/debug/routes", async ctx =>
            {
                await ctx.Response.WriteAsync(string.Join(", ", endpoints.DataSources.SelectMany(x => x.Endpoints)));
            });
        });

    }
}

here's a sample controller:

public class Home : Controller
{
    private readonly DatabaseContext _databaseContext;

    public Home(DatabaseContext databaseContext)
    {
        Console.WriteLine($"Initialized home controller"); // This doesn't get called at all.
        _databaseContext = databaseContext;
        _databaseContext.Database.EnsureCreated();

    }

    [HttpGet("/home")]
    public IActionResult Index()
    {
        ViewData["Products"] = _databaseContext.Products.ToList();
        return View();
    } 
    .....

and whenever I launch the server it I would go to /home and it would return 404, I also go to /debug/routes and it would show only the 2 endpoints inside the UseEndpoints function but never the controller classes I made

CodePudding user response:

Try registering you db context in service as below. You could be getting error due to dependency of DatabaseContext on your HomeController would not be able to resolve.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add below line
    services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connectionString));
    services.AddControllersWithViews();
}

CodePudding user response:

In the Configure(IApplicationBuilder app, IWebHostEnvironment env) method of the Startup class you need something like: app.MapControllers();

I think you controllers are registered to DI throught the call services.AddControllersWithViews(); but there is no middleware registration to invoke your controllers, wich should be done in the Configure method.

  • Related