如何在mvc3 Web应用程序中设置特定路由

时间:2012-11-22 10:30:21

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

我遇到路由问题。我的网站上有很多页面是从数据库动态生成的。

我想要完成的第一件事是路由到这些页面:

“如何修车”

www.EXAMPLE.com/How-to-repair-a-car

目前它的工作原理如下:www.EXAMPLE.com/Home/Index/How-to-repair-a-car

其次我的默认页面必须是这样的:www.EXAMPLE.com

在起始页面上将是有新闻的新闻,所以如果有人点击“第2页”按钮,那么地址应该是:www.EXAMPLE.com/page = 2

结论:

  1. 默认页面 - > www.EXAMPLE.com(页数= 0)
  2. 具有特定新闻页面的默认页面 - > www.EXAMPLE.com/page=12
  3. 文章页面 - > www.EXAMPLE.com/How-to-repair-car(没有参数'page')路由sholud指向文章或error404
  4. PS:对不起我的英文

2 个答案:

答案 0 :(得分:1)

尝试为路由配置中的文章创建路径,如下所示:

路由配置:

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

HomeController中:

public class HomeController : Controller
    {
        public ActionResult Index(int? page)
        {
            var definedPage = page ?? 0;
            ViewBag.page = "your page is " + definedPage;
            return View();
        }

        public ActionResult Article(string article)
        {
            ViewBag.article = article;
            return View();
        }
    }

/?page = 10 - 作品

/如何修理汽车 - 工作

这种做法非常出色。

答案 1 :(得分:0)

以下是www.example.com/How-to-repair-car

的基本路由示例
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Tipser.Web
{
    public class MyMvcApplication : HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                "ArticleRoute",
                "{articleName}",
                new { Controller = "Home", Action = "Index", articleName = UrlParameter.Optional },
                new { userFriendlyURL = new ArticleConstraint() }
                );
        }

        public class ArticleConstraint : IRouteConstraint
        {
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                var articleName = values["articleName"] as string;
                //determine if there is a valid article
                if (there_is_there_any_article_matching(articleName))
                    return true;
                return false;
            }
        }
    }
}