Paul Duer
Paul Duer

Reputation: 1120

How do I make a true default route for a MVC CORE project?

I have the following setup for my HomeController. I want all my MVC controllers to respond from /mvc/[controler]/[action] and the WebApi ones on /api/

But when someone goes to the no-path version of the host, I want it to go to /mvc/home/index, my setup doesn't seem to do that!

I want http://hostname/ to got to http:/hostname/Home/Index

    [Route("mvc/[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class HomeController : Controller
{
    [Route("Index")] 
    public IActionResult Index()
    {
        return View();
    }

    [Route("Error")]
    public IActionResult Error()
    {
        return View();
    }
}

my startup.cs:

      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseMiddleware(typeof(ErrorHandlingMiddleware));
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                "default",
                "mvc/{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            var swaggerendpoint = Configuration["SwaggerEndpoint"];
            c.SwaggerEndpoint(swaggerendpoint, "Public Cloud Interface");
        });
    }
}

Upvotes: 0

Views: 835

Answers (1)

Chris F Carroll
Chris F Carroll

Reputation: 12360

Add a route specifically for the / case:

app.UseMvc(routes =>
    {
        routes.MapRoute(
            "home",
            "/", 
            new{controller="Home", Action="Index"});

        routes.MapRoute(
            "default",
            "mvc/{controller=Home}/{action=Index}/{id?}");
    });

Upvotes: 2

Related Questions