向URL添加文本而不是int ID

时间:2018-05-19 13:40:15

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

目前,我们的固定链接不正确,阻碍搜索,例如https://example.com/en/blogs/19 - 这应该包含Google可以在搜索中找到的网址,而不是用于从Db检索的int id

让我们说一篇关于'汽车行业最新'的文章如果我们能够编辑包含关键字的链接,谷歌将会更加重视算法。例如: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重写,但如果可能的话,我希望远离这个。

1 个答案:

答案 0 :(得分:3)

引用Routing in ASP.NET Core

  

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

引用Routing to Controller Actions in ASP.NET Core

您可以应用路由约束以确保[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); } } 和标题不会相互冲突以获得所需的行为。

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

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

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

所以现在你的链接可以包含有助于链接到所需文章的搜索友好词汇

public class Test {
    private int a;
    private int b;
    private int c;
    private int d;

    public Test(int a, int b, int c, int d) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }

    public Test(int a, int b) {
        this.a = a;
        this.b = b;
        this.c = 0;
        this.d = 0;

        // or: this(a, b, 0, 0);
    }

    public Test() {
        this(5, 1, 0, 0);
    }
}

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