ASP.NET MVC 路由中未传递参数值
我正在学习如何在 ASP.NET MVC 中创建自定义路由,但遇到了困难。在我的 Global.asax.cs 文件中,我添加了以下内容:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
这个想法是让我能够导航到 http://localhost:123/home/filter/mynameparam
。这是我的控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
当我导航到 http://localhost:123/home/filter/mynameparam
时,调用控制器方法 Filter
,但参数 name
始终为null
。
有人可以指导我构建自定义路由的正确方法,以便将 url 中的名称部分传递到 Filter()
的 name
参数中。
I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've added the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
The idea is for me to able to navigate to http://localhost:123/home/filter/mynameparam
. Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
When I navigate to http://localhost:123/home/filter/mynameparam
the contoller method Filter
is called, but the parameter name
is always null
.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name
parameter for Filter()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Default
路由应该是最后一个。试试这样:
The
Default
route should be the last one.Try it this way:
我相信你的路线需要相反?
路由按顺序处理,因此如果第一个(默认,OOTB)路由与 URL 匹配,则将使用该路由。
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.