编程语言
首页 > 编程语言> > c#-将文本而不是int ID添加到URL

c#-将文本而不是int ID添加到URL

作者:互联网

目前,我们的固定链接不正确,并阻碍了搜索,例如https://example.com/zh-CN/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();
    }
}

我猜这仍然不会被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);
    }
}

这遵循与StackOverflow为其链接执行的类似模式

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

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

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

我建议在将博客保存到数据库时,根据博客标题将其生成为字段/属性,并确保清除所有无效URL字符的标题衍生信息.

标签:asp-net-core-webapi,asp-net-core-2-0,asp-net-core-routing,c
来源: https://codeday.me/bug/20191109/2010909.html