【问题标题】:Using easy custom routing使用简单的自定义路由
【发布时间】:2014-01-11 04:20:09
【问题描述】:

这是我第一次在 ASP.Net Mvc 上处理路由,我正在尝试像 StackOverflow 那样处理它的问题。

我的控制器名为News,它有他的动作,如News/News/CreateNews/Edit/1 等。我想添加这个自定义路由News/1,它将返回新闻本身的可视化,而不是默认索引News/ 显示的网格。

这些是我的路线:

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

routes.MapRoute(
    name: "ViewNews",
    url: "{controller}/News/{newsId}",
    defaults: new { controller = "News", action = "Index" },
    constraints: new { newsId = @"\d+" }
);

第一个是默认路由,第二个是我现在尝试的,跟随this post。但它只是给了我这个错误(在这个网址上News/1):

“/”应用程序中的服务器错误。

找不到资源。

我想知道我做错了什么,一旦它甚至没有达到行动。如果我尝试News/,效果很好。

我已经通过我的行动做到了这一点:

public ActionResult Index(int? id)
{
    if (id != null)
    {
        var news = _newsService.GetView((int)id);

        if (news != null)
        {
            return View("News", news);
        }
        else 
        {
            return RedirectToAction("Index", "Home");
        }
    }

    return View();
}

如果有人能告诉我该怎么做,那就太好了:News/1/news-title-here

【问题讨论】:

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


    【解决方案1】:

    这是因为News/ 匹配默认路由。

    您可能正在寻找这个:

    routes.MapRoute(
        name: "ViewNews",
        url: "News/{newsId}",
        defaults: new { controller = "News", action = "Index" },
        constraints: new { newsId = @"\d+" }
    );
    
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    请注意,您应该将最重要的路线放在第一位,因为它将按该顺序处理。此路由将匹配任何以 News 开头并根据您的约束具有 newsId 的 url,并将其路由到 News 控制器的 Index 操作。

    附带说明:{newsId} 指的是操作中具有相同名称的参数。所以你的索引设置应该是这样的:

    public class NewsController : Controller
    {
        public ActionResult Index(int newsId)
        {
        }
    }
    

    如果您希望接受像 News/1/news-title-here 这样的虚拟参数,您可以使用以下路由:

    routes.MapRoute(
        name: "ViewNews",
        url: "News/{newsId}/{customTitle}",
        defaults: new { controller = "News", action = "Index",
                        customTitle = UrlParameter.Optional },
        constraints: new { newsId = @"\d+" }
    );
    

    【讨论】:

    • 好吧,我没想到这会有什么不同。我会试试的。
    • 是的,我意识到我应该将操作参数更改为newsId。成功了,伙计,谢谢。
    • @DontVoteMeDown 没问题,很高兴我能帮上忙。
    • 您知道如何使用我的网址,例如News/1/news-title-here 吗?如果问你的时间不算太多。
    • 哎呀,太简单了。再次感谢老哥!我必须阅读并了解更多有关此主题的内容!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多