c# - 将 Rails 路由转换为 Asp.net MVC 路由

标签 c# ruby-on-rails asp.net-mvc

我正在将 Rails 应用程序的路由转换为与替换的 Asp.net MVC 应用程序一起使用。我们需要维护所有旧网址。大多数路线都可以毫无问题地转换 - 但我有点难以弄清楚如何处理这条路线......

实际的url都是这样连字符的

site.com/agent-name-ratings-city-name-123

Rails 路线定义为

get '/:agent_name-ratings-:city-:id' => 'agents#show'

我只需要将“agent-name”作为 {id} 传递给 Asp {agents} Controller 。我的问题是如何处理 url 末尾的城市名称和 ID...?

我试过以下方法:

routes.MapRoute(name: "agents", url: "{id}-ratings-{city}-{agent_id}", defaults: new { controller = "Agents", action = "Profiles", id = "{id}" });

这有效,但是 - 它似乎弄乱了 @Html.ActionLink...

@Html.ActionLink("View",  "Profiles", "Agents",  new { id = item.first_name + "-" + item.last_name }, null)

它最终指向...

site.com/Agents/Profiles/agent-name

这是一个有效的 url,只是不是我们想要的。

那么 - 如何以所需的格式获取此链接?

site.com/agent-name-ratings-city-123

城市名称和 ID 都可以从“项目”对象中获得。 “收视率”这个词是一个常数。我只是不确定如何将它们混合在一起。

如有任何建议,我们将不胜感激!

最佳答案

主要问题是您在路由中指定了 Url 参数,但是它们没有出现在您的 Html.ActionLink 定义中,因此默认路由被使用,因为没有明确的匹配。

尝试以下操作:

@Html.ActionLink("View",  "Profiles", "Agents",  new { id = item.first_name + "-" + item.last_name, city = item.city, agent_id = item.agent_id }, null)

否则,将 UrlParameter.Optional 添加到 map 路由中的 2 个附加字段。

routes.MapRoute(
            name: "agents", 
            url: "{id}-ratings-{city}-{agent_id}", 
            defaults: new { controller = "Agents", action = "Profiles", id = "{id}", city = UrlParameter.Optional, agent_id = UrlParameter.Optional });

但是,如果您仅在操作链接中指定 id 部分,则将参数设为可选将导致 URL 格式错误。 例如site.com/agent-name-ratings--

编辑

同时使 Url 参数成为可选参数很可能会破坏在参数中指定 id 的其他路由。然而,这可能会起作用,并且不会破坏太多东西,但仍然会有格式错误的 URL:

@Html.ActionLink("View", "Profiles", "Agents", new { agent_name = "agent" + "-" + "name" }, null)

routes.MapRoute(
            name: "agents", 
            url: "{agent_name}-ratings-{city}-{agent_id}",
            defaults: new { controller = "Agents", action = "Profiles", agent_name = "{agent_name}", city = UrlParameter.Optional, agent_id = UrlParameter.Optional });

关于c# - 将 Rails 路由转换为 Asp.net MVC 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31688408/

相关文章:

ruby-on-rails - 如何使用 reduce 方法改进此总和

asp.net-mvc - Log4Net 在开发机器上工作,部署到共享主机时失败(使用相同的 db/connstring)

C# - 验证模拟(MoQ)属性的方法是用部分字符串作为参数调用的

ruby-on-rails - ActionView::Template::Error Webpacker 找不到应用程序包

c# - 无法初始化类型 'int' 错误

ruby-on-rails - 良好的后台处理选项

c# - 从另一个属性值设置的 ASP.NET MVC 数据注释属性范围

c# - 我应该在 ViewModel(UI 层)和域模型(业务层)中使用相同的枚举定义吗?

c# - UWP MapControl 放大后崩溃

c# - 如何检查 Button.Tag 的首字母?