【问题标题】:Routing without Action Name in Url在 URL 中没有操作名称的路由
【发布时间】:2015-02-27 17:41:45
【问题描述】:

我遇到了路由问题。我有新闻控制器,我可以从 url http://localhost/News/Details/1/news-title(slug) 阅读新闻的详细信息。这里暂时没有问题。但我创建了一个名为 Services 和 Index 操作的控制器。路线配置:

routes.MapRoute(
    "Services",
    "Services/{id}",
    new { controller = "Services", action = "Index" }
); 

当我的索引操作是

public ActionResult Index(string title)
{
    return View(title);
}

我在浏览器中手写localhost:5454/Services/sometext,它可以工作。

但是当我将索引操作更改为

public ActionResult Index(string title)
{
    Service service = _myService.Find(title);
    ServiceViewModel = Mapper.Map<Service , ServiceViewModel >(service );
    if (service == null)
    {
        return HttpNotFound();
    }
    return View(serviceViewModel);
}

我收到 URL localhost/Services/ITServices 的 Http 错误 404。

我可以从管理页面添加此服务及其标题(例如 ITServices)。 然后我在我的主页中为服务链接做 foreach

@foreach (var service Model.Services)
{
    <div class="btn btn-success btn-sm btn-block">
     @Html.ActionLink(service.Title, "Index", new { controller = "Services", id = service.Title }) 
    </div>
}

但我无法在localhost/Services/ITServices 中显示页面。

当我点击链接时,我想转到页面 localhost/Services/ITServices,它必须像新闻一样显示内容(可以从管理页面添加)。但我不想像新闻中那样将它与动作名称和 ID 一起使用。我怎样才能做到这一点?

编辑

好的。我在存储库中添加FindByTitle(string title)。我在 RouteConfig 和主页视图的链接中将 id 更改为 title。然后在我的域模型中删除 Id 并将 Title 更新为 [Key]。现在它起作用了。从管理页面添加新标题时,只需通过远程验证检查可能的标题重复项。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-routing action


    【解决方案1】:

    URL 模板中的参数名称与 Action 上的参数不匹配 (Index)。

    所以你可以做两件事之一。

    更改模板参数以匹配 Action 的参数

    routes.MapRoute(
       name: "Services",
       url: "Services/{title}",
       defaults: new { controller = "Services", action = "Index" }
    ); 
    

    动作索引在哪里

    public ActionResult Index(string title) { ... }
    

    或者你改变 Action Index 的参数来匹配 url 模板中的参数

    public ActionResult Index(string id) { ... }
    

    路由映射在哪里

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

    但是无论哪种方式,路由都找不到路由,因为它无法匹配参数。

    事实上,如果您打算将标题用作 slug,那么您甚至可以对诸如

    之类的服务使用包罗万象的路线
    routes.MapRoute(
       name: "Services",
       url: "Services/{*title}",
       defaults: new { controller = "Services", action = "Index" }
    ); 
    

    看看这里提供的答案

    how to route using slugs?

    Dynamic routing action name in ASP.NET MVC

    【讨论】:

      【解决方案2】:

      试试这个:

      public ActionResult Index(string id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 2017-09-23
        • 1970-01-01
        • 2014-12-01
        • 2013-09-10
        • 2017-01-04
        相关资源
        最近更新 更多