向 URL 添加文本而不是 int ID

Add text to URLs instead of int ID

目前我们的 permalinks 不正确并且妨碍搜索,例如https://example.com/en/blogs/19 - 这应该在 URL 中包含 Google 可以在搜索中获取的单词,而不是用于从 Db 检索的 int id

假设 'The Automotive Industry Latest' Google 的文章将在算法中赋予更多权重,如果我们能够编辑包含关键字的 link。例如:https://example.com/en/blogs/news/The_Automotive_Industry_Latest - 这个 link 应该指向 https://example.com/en/blogs/19

我可以使用以下方法完成此操作 - 但这是实现此目的的方法吗?

[Route("en/blogs")]
public class BlogController : Controller
{
    [HttpGet("{id}")]
    [AllowAnonymous]
    public IActionResult GetId([FromRoute] int id)
    {
        var blog = _context.Blogs.Where(b => b.Id == id);

        return Json(blog);
    }

    [HttpGet("{text}")]
    [AllowAnonymous]
    public IActionResult GetText([FromRoute] string text)
    {
        var blog = _context.Blogs.Where(b => b.Title.Contains(text));

        if(blog != null)
            GetId(blog.Id)

        return Ok();
    }
}

我猜这仍然不会被 Google 索引为文本,所以必须通过 sitemap.xml 来完成?这一定是一个常见的要求,但我找不到关于它的任何文档。

我知道 IIS URL 重写,但如果可能的话我想远离它。

引用 Routing in ASP.NET Core

You can use the * character as a prefix to a route parameter to bind to the rest of the URI - this is called a catch-all parameter. For example, blog/{*slug} would match any URI that started with /blog and had any value following it (which would be assigned to the slug route value). Catch-all parameters can also match the empty string.

引用 Routing to Controller Actions in ASP.NET Core

您可以应用路由约束以确保 id 和标题不会相互冲突以获得所需的行为。

[Route("en/blogs")]
public class BlogController : Controller {
    //Match GET en/blogs/19
    //Match GET en/blogs/19/the-automotive-industry-latest
    [HttpGet("{id:long}/{*slug?}",  Name = "blogs_endpoint")]
    [AllowAnonymous]
    public IActionResult GetBlog(long id, string slug = null) {
        var blog = _context.Blogs.FirstOrDefault(b => b.Id == id);

        if(blog == null)
            return NotFound();

        //TODO: verify title and redirect if they do not match
        if(!string.Equals(blog.slug, slug, StringComparison.InvariantCultureIgnoreCase)) {
            slug = blog.slug; //reset the correct slug/title
            return RedirectToRoute("blogs_endpoint",  new { id = id, slug = slug });
        }

        return Json(blog);
    }
}

这遵循与 Whosebug 对其链接所做的类似模式

questions/50425902/add-text-to-urls-instead-of-int-id

现在您的链接可以包含搜索友好词,这应该有助于链接到所需的文章

GET en/blogs/19
GET en/blogs/19/The-Automotive-Industry-Latest.

我建议在将博客保存到数据库时根据博客标题将 slug 生成为 field/property,确保清除标题派生的任何无效 URL 字符的 slug。