无法找到Asp.net MVC 4 Url Resource

时间:2013-03-12 08:42:47

标签: c# asp.net-mvc asp.net-mvc-4

在我的索引页面中,我使用以下

生成网址
@foreach(var c in ViewBag.cities)
{
   <li>@Html.ActionLink((string)c.CityName,"somepage",new{city=c.CityName, id=c.Id})</li>
}

以下列格式生成每个城市的网址

localhost:55055/1/city1
localhost:55055/2/city2
...

其中1,2是Id和city1,city2是CityName

我已将路线配置为

routes.MapRoute(
            name: "CityRoute",
            url: "{id}/{city}",
            defaults: new { controller = "Home", action = "somepage", id = UrlParameter.Optional, city = UrlParameter.Optional }
            );

Home Controller中的somepage操作方法:

public string somepage(int id, string city)
{
  return city + " " + id;
}

即使我尝试了这个

public string somepage()
{
   return "Hello";
}

但会产生Resource cannot be found

我尝试在sompage中放置一个永不被击中的断点。

任何建议

更新

正如@KD在下面的评论中所指出的,我改变了路线顺序并将上述规则置于所有规则之上。我也改变了方法

 public ActionResult somepage(int id=0, string city="")
 {
    return Content(city + " " + id);
 }

现在行为已更改,默认规则为

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

不用于普通索引页面。而是使用此用法,因为方法somepage中的断点被命中,如果我将http://localhost:55055/2/cityname放入浏览器,则页面会显示id和cityname。但现在默认路由不用于应用程序主目标http://localhost:55055/

2 个答案:

答案 0 :(得分:4)

新路线的模式和默认路线的模式几乎相同,因此它总是会产生冲突以匹配这些路线。将路线改为以下

routes.MapRoute(
            name: "CityRoute",
            url: "CitySearch/{id}/{city}",
            defaults: new { controller = "Home", action = "somepage", id = UrlParameter.Optional, city = UrlParameter.Optional }
            );

即。为您的模式添加一些前缀,以便轻松识别..如“CitySearch” 然后在提供行动链接时提及您的路线名称..

或者,如果您不想为其添加前缀,请执行以下操作,它将像魅力一样工作..

对于您的CityRoute,为ID添加路径约束,以检查ID字段是否为整数。对于普通的URL,它将返回false,因此您的默认路由将被评估...尝试此...

routes.MapRoute(
            name: "CityRoute",
            url: "{id}/{city}",
            defaults: new { controller = "Home", action = "somepage", id = UrlParameter.Optional, city = UrlParameter.Optional },
            constraints: new {id = @"\d+"}
            );

这是正则表达式约束。将此路线置于顶部并检查。

答案 1 :(得分:0)

由于您尚未定义Action,因此不会调用它,因此错误即将来临

试试这个,

public ActionResult somepage(int id, string city)
    {
        return Content(city + " " + id);
    }