3

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

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

“如何修理汽车”

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

现在它是这样工作的:www.EXAMPLE.com/Home/Index/How-to-repair-a-car

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

在起始页上会有分页新闻,所以如果有人点击“page 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(不带参数“页面”)路由应指向文章或错误404

PS:对不起我的英语

4

2 回答 2

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 }
            );
        }
    }

家庭控制器:

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 - 有效

/如何修理汽车 - 工作

这种方法非常有效。

于 2012-11-22T10:49:57.757 回答
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;
            }
        }
    }
}
于 2012-11-22T10:41:20.417 回答