如何在.NET 6 Razor Pages中生成含多属性的SEO友好URL?
在.NET 6 Razor Pages中生成SEO友好URL
1. 修改视图中的链接生成代码
在生成文章链接的视图(比如文章列表页)中,除传递id外,额外添加category、topic、urlTitle路由参数,确保视图能访问到PostViewModel实例:
<!-- 假设视图模型为IEnumerable<PostViewModel>,循环生成链接 --> @foreach (var post in Model.Posts) { <a asp-page="/Post" asp-route-id="@post.Id" asp-route-category="@post.Category.ToLowerInvariant()" asp-route-topic="@post.Topic.ToLowerInvariant()" asp-route-urlTitle="@post.UrlTitle"> @post.Title </a> }
2. 配置自定义路由模板
在Program.cs中为Post页面设置SEO友好的路由结构:
builder.Services.AddRazorPages(options => { // 为Post页面绑定自定义路由,约束id为整数,其余参数为字符串(可按需调整约束规则) options.Conventions.AddPageRoute("/Post", "post/{id:int}/{category}/{topic}/{urlTitle}"); });
3. 调整页面处理器(可选但推荐)
页面处理器仅需id即可获取文章数据,但为保证URL正确性和SEO优化,可添加参数校验,自动重定向到正确地址:
[BindProperty] public PostViewModel? Post { get; set; } public async Task<IActionResult> OnGetAsync(int id, string? category = null, string? topic = null, string? urlTitle = null) { Post = await _postService.GetPostAsync(id); if (Post == null) { return NotFound(); } // 标准化SEO参数(转为小写,确保与实际数据一致) var expectedCategory = Post.Category.ToLowerInvariant(); var expectedTopic = Post.Topic.ToLowerInvariant(); var expectedUrlTitle = Post.UrlTitle.ToLowerInvariant(); // 校验URL参数是否匹配实际数据,不匹配则重定向到正确URL if (!string.Equals(category?.ToLowerInvariant(), expectedCategory) || !string.Equals(topic?.ToLowerInvariant(), expectedTopic) || !string.Equals(urlTitle?.ToLowerInvariant(), expectedUrlTitle)) { return RedirectToPage("/Post", new { id = Post.Id, category = expectedCategory, topic = expectedTopic, urlTitle = expectedUrlTitle }); } return Page(); }
4. 预处理SEO参数(关键)
确保PostViewModel中的Category、Topic、UrlTitle符合URL规范:
- 统一转为小写
- 替换空格、特殊字符为连字符(
-) - 移除非ASCII字符(如需支持可做URL编码)
示例:在服务层获取数据时标准化属性:
public async Task<PostViewModel> GetPostAsync(int id) { var post = await _dbContext.Posts.FindAsync(id); if (post == null) return null; return new PostViewModel { Id = post.Id, Category = Slugify(post.Category), Topic = Slugify(post.Topic), UrlTitle = Slugify(post.Title), // 其他属性... }; } // 简单的Slug生成方法 private string Slugify(string input) { return input.ToLowerInvariant() .Replace(" ", "-") .Replace("[^a-z0-9-]", ""); // 移除非字母数字和连字符的字符 }
内容的提问来源于stack exchange,提问作者PixelPaul
相关产品推荐
相关产品推荐

