【问题标题】:Add text to URLs instead of int ID向 URL 添加文本而不是 int ID
【发布时间】:2018-10-29 18:08:28
【问题描述】:

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

假设一篇关于“汽车行业最新消息”的文章,如果我们能够编辑包含关键字的链接,Google 将在算法中给予更多的权重。例如:https://example.com/en/blogs/news/The_Automotive_Industry_Latest - 此链接应指向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();
    }
}

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

我知道 IIS URL 重写,但如果可能,我想远离这种情况。

【问题讨论】:

  • 一种常见的方法是重写你的url以包含id和标题,参见stackoverflow的url示例,例如:www.example.org/123/the-best-example-ever,要做到这一点,我认为创建一个MapHttpRoute是最简单的...我无法突然为您提供一个示例,我已经有一段时间没有这样做了

标签: c# asp.net-core-2.0 asp.net-core-webapi asp.net-core-routing


【解决方案1】:

引用Routing in ASP.NET Core

您可以使用 * 字符作为路由参数的前缀,以绑定到 URI 的其余部分 - 这称为 catch-all 参数。例如,blog/{*slug} 将匹配任何以 /blog 开头并在其后有任何值的 URI(将分配给 slug 路由值)。包罗万象的参数也可以匹配空字符串。

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

这与 StackOverflow 为其链接所做的模式类似

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

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

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

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

【讨论】:

    猜你喜欢
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2012-03-18
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多