You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将URL中的Int ID替换为文本以优化永久链接搜索权重?

Let's break down your problem step by step to fix your SEO-friendly URLs and ensure proper indexing:

1. Fixing Your Controller Routing & Logic

First, your current code has a critical issue: ASP.NET Core can't distinguish between the {id} and {text} route parameters (both are just route segments), so it'll throw an ambiguous match error. Here's a corrected, SEO-friendly approach:

Key Changes:

  • Add a unique Slug field to your Blog entity (store a clean, keyword-rich string derived from the title, e.g., the-automotive-industry-latest instead of The_Automotive_Industry_Latest—search engines prefer hyphens over underscores).
  • Use 301 permanent redirects for old ID-based URLs to preserve existing SEO weight.
  • Match against the unique slug instead of using Title.Contains (which can return multiple results).
[Route("en/blogs")]
public class BlogController : Controller
{
    private readonly YourDbContext _context;

    public BlogController(YourDbContext context)
    {
        _context = context;
    }

    // Handle old ID-based URLs: redirect permanently to slug URL
    [HttpGet("{id:int}")]
    [AllowAnonymous]
    public IActionResult GetById(int id)
    {
        var blog = _context.Blogs.FirstOrDefault(b => b.Id == id);
        if (blog == null) return NotFound();
        
        // 301 tells search engines to update their index to the new URL
        return RedirectPermanent($"/en/blogs/{blog.Slug}");
    }

    // Handle SEO-friendly slug URLs
    [HttpGet("{slug}")]
    [AllowAnonymous]
    public IActionResult GetBySlug(string slug)
    {
        // Case-insensitive match to avoid issues with capitalization
        var blog = _context.Blogs.FirstOrDefault(b => 
            b.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase));
        
        if (blog == null) return NotFound();
        
        return Json(blog); // Or return your view with blog content
    }
}

Bonus: Auto-Generate Slugs

Add an extension method to create clean slugs from titles (run this when creating/updating a blog post):

public static string ToSlug(this string input)
{
    if (string.IsNullOrEmpty(input)) return string.Empty;
    
    // Convert to lowercase
    var slug = input.ToLowerInvariant();
    // Remove non-alphanumeric characters
    slug = Regex.Replace(slug, @"[^a-z0-9\s-]", "");
    // Replace multiple spaces/hyphens with a single hyphen
    slug = Regex.Replace(slug, @"[\s-]+", "-");
    // Trim leading/trailing hyphens
    slug = slug.Trim('-');
    
    return slug;
}
2. Ensuring Google Indexes Your URLs

You're right to ask about sitemaps—they help Google discover and index your content faster, especially new posts. You don't need IIS URL Rewrite for this; you can generate a dynamic sitemap directly in ASP.NET Core:

Example Sitemap Controller

[Route("sitemap.xml")]
[AllowAnonymous]
public IActionResult Sitemap()
{
    var blogs = _context.Blogs.Select(b => new 
    {
        Url = $"https://example.com/en/blogs/{b.Slug}",
        LastModified = b.UpdatedDate ?? b.CreatedDate
    }).ToList();

    var xml = new XDocument(
        new XDeclaration("1.0", "utf-8", "yes"),
        new XElement("urlset",
            new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"),
            from blog in blogs
            select new XElement("url",
                new XElement("loc", blog.Url),
                new XElement("lastmod", blog.LastModified.ToString("yyyy-MM-dd"))
            )
        )
    );

    return Content(xml.ToString(), "application/xml");
}

Additional Indexing Tips:

  • Avoid duplicate content: The 301 redirect from ID to slug URLs ensures Google only indexes the SEO-friendly version.
  • Optimize page metadata: Add unique <title> and <meta name="description"> tags to each blog post page—these help Google understand your content and improve rankings.
  • Submit your sitemap: Use Google Search Console to submit your sitemap.xml URL directly, so Google knows to crawl it regularly.
3. Final Notes
  • Always use hyphens (-) in slugs—search engines treat them as word separators, while underscores (_) are treated as a single word.
  • Keep slugs concise (remove filler words like "the", "a", "an") while retaining key keywords from the title.
  • Ensure slugs are unique in your database to avoid routing conflicts.

内容的提问来源于stack exchange,提问作者Paolo B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:02:57