正确设置SEO友好博客的自定义路由

本文关键字:自定义 路由 设置 SEO | 更新日期: 2023-09-27 18:34:13

我希望使用 MVC 4 为我的博客提供一条 SEO 友好的路线。 我已经查看了几篇堆栈溢出文章并尝试利用该建议,但我仍然无法使其正常工作。

我尝试做的是,当有人点击其中一篇博客文章时,路线会显示:blog/{blogCategory}/{blogTitle},例如"blog/clean/how-to-remove-tainins"。 我错过了一些重要的东西。 我已经包括了控制器,视图和路由。我有两个问题:

  1. 为什么当我将blogTitle("西班牙的雨"(传递给控制器时,它会带有连字符和空格? 我希望能够获取标题并通过一个函数运行它,使其对 URL 友好,并将其放回以显示在路由中。

  2. 为什么该路线只能部分工作? 它不显示 blog/{blogCategory}/{blogTitle},而是显示 blog/{blogCategory}?查询字符串,请参见以下示例:blog/unclassd/the%20-rain%20in%20-spain%20-falls%20-mainly%20on%20the%20-plains?id=2。(注:未分类是类别之一(

路由配置:

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.Canonicalize().NoWww().Pattern("([a-z0-9])([A-Z])", "$1-$2").Lowercase().NoTrailingSlash();
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
            "Blog",
            "Blog/{blogCategory}/{blogTitle}",
            new { controller = "Blog", action = "Details" }
            ).RouteHandler = new Spotless_Interiors.Models._GlobalClasses.HyphenatedRouteHandler();
            // Original route map
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            ).RouteHandler = new Spotless_Interiors.Models._GlobalClasses.HyphenatedRouteHandler(); 

        }
    }

视图:

@model Spotless_Interiors.Models.MultiModels
@{
    ViewBag.Title = "Blog";
    ViewBag.Separator = " | ";
    ViewBag.Path = Request.Path;
}

@section menuLeft {
    @Html.Partial("_BlogMenu")
}
@Html.Partial("_TitleBlockPartial", Model.Company)
@if (User.Identity.IsAuthenticated) {
    <div class="blog-links">            
        @Html.ActionLink("Create New", "Create", "Blog", new { DT_Stamp = @DateTime.Now })
        @ViewBag.Separator
        <a href="@Url.Action("Meta-Tag-Editor", "Dashboard", new { pageName = (string)ViewBag.pageName, path = (string)ViewBag.Path })" >MetaTag</a> 
        <hr />
    </div> 
}
<div id="blog">
    @foreach (var item in Model.PagedPosts)
    {

            <h1>@Html.ActionLink(item.Title, "Details", new { id = item.PostID, blogCategory = item.Category.CategoryName, blogTitle = item.Title }, new { @class ="blog-title" }) </h1>  
            <div class="full-width">
                <div class="blog-category">  
                    <h2>@Html.DisplayFor(modelItem => item.Category.CategoryName) |  @Html.DisplayFor(modelItem => item.DT_Stamp)</h2> 
                </div>
                <div class="blog-links"> 
                    @Html.ActionLink("Read More >>", "Details", new { id = item.PostID, blogCategory = item.Category.CategoryName, blogTitle = item.Title }, new { @class ="blog-links" })
                </div>
            </div>
            <div class="full-width">
            </div>
                @Html.Raw(Server.HtmlDecode(item.TruncatedBody.Replace("<img ", "<img style = 'width:100px' ")))

            <div class="ribbon" style="clear:both"></div>            
    }
</div>

控制器:

// GET: /Blog/Details
        public ActionResult Details(int id = 0, string blogCategory = "", string blogTitle = "")
        {
            pageName = "Blog Details";
            ViewBag.pageName = pageName;
            var multiModels = _globalClasses.Standard(ViewBag.pageName, Request.Path);
            ///multiModels.Post = db.Posts.First(i => i.PostID == id);
            multiModels.Post = db.Posts.First(i => i.PostID == id);
            multiModels.PostComments = db.PostComments.Where(i => i.PostPostID == id).ToList();

            blogTitle = _globalClasses.UrlFriendly(blogTitle);

            if (multiModels.Post == null)
            {                
                return HttpNotFound();
            }
            return View(multiModels);
        }

正确设置SEO友好博客的自定义路由

也许您的自定义扩展方法Canonicalize (?( 和自定义路由处理程序会把事情搞砸。

关于 ASP.NET MVC,这就足够了:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(name:"Blog", url:"Blog/{blogCategory}/{blogTitle}",
                    defaults:new {controller = "Blog", action = "Details"});
    routes.MapRoute(name:"Default", url:"{controller}/{action}/{id}",
                    defaults:new {controller = "Home", action = "Index", id = UrlParameter.Optional});
}

和控制器:

public class BlogController : Controller
{
    public ActionResult Details(string blogCategory, string blogTitle)
    {
        return Content(string.Format("category: {0}, title: {1}", blogCategory, blogTitle));
    }
}

对于路径/blog/my%20category/my%20title,您会得到正确的响应"category: my category, title: my title"