如何为MVC CORE项目创建真正的默认路由?

时间:2017-03-28 19:55:10

标签: c# asp.net-core asp.net-core-mvc asp.net-mvc-routing

我的HomeController有以下设置。我希望我的所有MVC控制器都响应来自/ mvc / [controler] / [action]以及/ api /

上的WebApi控制器

但是当有人进入主机的无路径版本时,我希望它转到/ mvc / home / index,我的设置似乎没有这样做!

我希望http://hostname/能够访问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();
    }
}

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

1 个答案:

答案 0 :(得分:2)

专门为/案例添加路线:

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

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