当动作有 2 个参数时找不到路线 - Asp.Net MVC
cant find Route when action has 2 params - Asp.Net MVC
我有一个名为 Blog
的控制器。
我有这样的操作:
[Route("{code:int}/{title?}")]
public virtual ActionResult Index(int code, string title)
{
var postModel = _blogService.Get(code.ToUrlDecription());
return View(postModel);
}
我输入了这些网址,但都返回未找到:
localhost:7708/Blog/index/12/post-title
;
localhost:7708/Blog/index/12
;
localhost:7708/Blog/12/post-title
.
我试着写了一个如下的路由,但是结果是一样的:
routes.MapRoute(
name: "showblogpost", url: "{controller}/{action}/{code}/{title}",
defaults: new {
controller = "Blog",
action = "Index",
title = UrlParameter.Optional
},
namespaces:new string[] { "Web.Controllers" }
);
有一件事,你不需要在动作和映射路线上同时使用属性[Route]
。
在您的属性 [Route]
中您只指定了参数,因此根据它的路由应该是 localhost:7708/12
按路线,在MapRoute
中指定应该是localhost:7708/showblogpost/12
我的建议是 - 删除你的属性,在 MapRoute
中命名你的路线,就像你想在 URL 中看到的那样,你也可以从操作中删除 "string title" 参数,因为没用过。
我有一个名为 Blog
的控制器。
我有这样的操作:
[Route("{code:int}/{title?}")]
public virtual ActionResult Index(int code, string title)
{
var postModel = _blogService.Get(code.ToUrlDecription());
return View(postModel);
}
我输入了这些网址,但都返回未找到:
localhost:7708/Blog/index/12/post-title
;localhost:7708/Blog/index/12
;localhost:7708/Blog/12/post-title
.
我试着写了一个如下的路由,但是结果是一样的:
routes.MapRoute(
name: "showblogpost", url: "{controller}/{action}/{code}/{title}",
defaults: new {
controller = "Blog",
action = "Index",
title = UrlParameter.Optional
},
namespaces:new string[] { "Web.Controllers" }
);
有一件事,你不需要在动作和映射路线上同时使用属性[Route]
。
在您的属性 [Route]
中您只指定了参数,因此根据它的路由应该是 localhost:7708/12
按路线,在MapRoute
中指定应该是localhost:7708/showblogpost/12
我的建议是 - 删除你的属性,在 MapRoute
中命名你的路线,就像你想在 URL 中看到的那样,你也可以从操作中删除 "string title" 参数,因为没用过。