MVC路由.net核心

Sré*_*áîr 5 c# asp.net-mvc asp.net-mvc-routing asp.net-core visual-studio-2017

在我以前的.net应用程序中,我以前在route.config中使用以下路由

routes.MapRoute(
name: "Default",
url: "{tenant}/{controller}/{action}/{id}",
defaults: new { tenant = "GRE", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

现在,我将移至.Net Core,但由于某种原因,我无法在startup.cs中设置类似的路由

我已经尝试过以下方法,但从未成功。

 app.UseMvc(routes =>
            {  
                routes.MapRoute("testroute", "{tenant}/{controller}/{action}/{id}",
                        defaults: new { tenant = "GRE", controller = "Home", action = "Index" });

            });
Run Code Online (Sandbox Code Playgroud)

HomeController.cs

public IActionResult Index(string tenant)
        {
            return View();
        }
Run Code Online (Sandbox Code Playgroud)

赞赏各种帮助或提示使其工作

谢谢,

Evk*_*Evk 3

您的id参数在您的 asp.net mvc 代码中是可选的,但在 asp.net core 代码中不是可选的,并且没有默认值,因此它不匹配。要使其可选,请添加“?” 名称,或设置默认值:

app.UseMvc(routes =>
{
    routes.MapRoute("testroute", "{tenant}/{controller}/{action}/{id?}",
        defaults: new { tenant = "GRE", controller = "Home", action = "Index" });

});
Run Code Online (Sandbox Code Playgroud)

您还可以内联设置默认值,如下所示:

routes.MapRoute("testroute", "{tenant=GRE}/{controller=Home}/{action=Index}/{id?}");
Run Code Online (Sandbox Code Playgroud)