You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中如何为对比模块实现SEO友好URL?

实现SEO友好URL的步骤

1. 配置自定义特性路由

在CompareController的ResultTwo Action上添加特性路由,指定SEO友好的URL匹配模板:

[Route("Compare/{nameOne}-vs-{nameTwo}")]
public IActionResult ResultTwo(string nameOne, string nameTwo)
{
    // 逻辑调整见下一步
}

这个模板会自动匹配/Compare/xxx-vs-yyy格式的URL,将xxx绑定到nameOne参数、yyy绑定到nameTwo参数。

2. 调整Action逻辑:从名称映射到ID

原Action接收的是ID参数,现在URL传递的是实体名称,需要新增逻辑根据名称查询对应ID(替换为你项目中实际的数据查询逻辑):

[Route("Compare/{nameOne}-vs-{nameTwo}")]
public IActionResult ResultTwo(string nameOne, string nameTwo)
{
    // 示例:通过服务/数据库根据名称获取ID
    var compareOneId = _entityService.GetIdBySlug(nameOne);
    var compareTwoId = _entityService.GetIdBySlug(nameTwo);

    // 处理查询不到ID的异常情况(可选,比如返回404)
    if (compareOneId == null || compareTwoId == null)
    {
        return NotFound();
    }

    _model.Item1 = Convert.ToInt16(compareOneId);
    _model.Item2 = Convert.ToInt16(compareTwoId);

    return View(FullPathsOfViews.CompareSpecs, _model);
}

注意:确保实体的名称(slug)是唯一的,避免ID查询出现歧义。

3. 修改前端URL生成逻辑

将原来生成带查询参数URL的代码,替换为生成新的SEO友好URL。比如在Razor视图中:

原来的代码:

<a href="@Url.Action("ResultTwo", "Compare", new { compareOne = item1.Id, compareTwo = item2.Id })">对比</a>

修改后:

<a href="@Url.Action("ResultTwo", "Compare", new { nameOne = item1.Slug, nameTwo = item2.Slug })">对比</a>

这样生成的URL就是/Compare/nvidia-vs-raiden格式。

可选:兼容旧URL(重定向)

如果需要保留对旧URL/Compare/ResultTwo?compareOne=4&compareTwo=2的支持,可以新增一个无特性路由的Action处理重定向:

// 处理旧URL,重定向到SEO友好URL
public IActionResult ResultTwo(string compareOne, string compareTwo)
{
    var nameOne = _entityService.GetSlugById(Convert.ToInt16(compareOne));
    var nameTwo = _entityService.GetSlugById(Convert.ToInt16(compareTwo));

    return RedirectToAction("ResultTwo", new { nameOne, nameTwo });
}

内容的提问来源于stack exchange,提问作者Prageeth Liyanage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:12:16