如何访问 ASP .NET MVC URL?

How to access ASP .NET MVC URL?

我正在通过观看 Mosh ASP .Net 教程来编写代码。但我堆在一件事上。我的路由 url 不工作,但查询字符串在工作。

这是我的代码:

路由代码

routes.MapRoute(
                "MovieByReleaseDate",
                "movie/released/{year}/{month}",
                new {controller = "Movie", action = "ByReleaseDate" }
                );

操作代码

public ActionResult ByReleaseDate(int year, int month)
        {
            return Content(year+"/"+month);
        } 

但 link 不工作。添加了屏幕截图 http://localhost:49941/Movie/ByReleaseDate/2015/12

but link is not working. screenshot added

处理查询 working this only screenshot added

您应该像这样编辑路由代码:

routes.MapRoute(
            "MovieByReleaseDate",
            "movie/released/{year}/{month}",
            new {controller = "Movie", action = "ByReleaseDate", year = 0 , month = 0 }
            );

在 URL 中你可以使用这样的东西

http://localhost:44360/movie/released/2021/1

--注意你的端口不同

如果您没有定义正确的路由,您将无法实现您的目标。 看来您需要更好地了解路由。

请参考 https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs

在您想要使用显式路由而不是使用查询字符串的情况下,您没有遵循约定。

尝试将默认值添加到路由定义中。

new {controller = "Movie", action = "ByReleaseDate" ,year=0, month=0 }

基本上,当您定义路由时,您需要定义接收信息的方式。

新{controller = "Movie", action = "ByReleaseDate"}
将允许您按照以下模式进行路由

  • {控制器}/{操作}
  • {控制器}/{操作}? “查询字符串”

new {controller = "Movie", action = "ByReleaseDate",year=0 }
将允许您按照以下模式进行路由

  • {控制器}/{操作}/年
  • {控制器}/{操作}? “查询字符串”
  • {控制器}/{操作}/年? “查询字符串”