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

ASP.NET Core项目中如何替换地址栏中的#字符为其他指定符号

核心前提

URL中的#属于哈希片段,浏览器默认不会将这部分内容发送到ASP.NET Core后端,所以必须先通过前端逻辑捕获哈希值,再完成格式转换。

方案1:前端直接转换(无后端修改成本,最简便)

在项目的全局布局页(通常是Views/Shared/_Layout.cshtml或者对应Razor组件的全局脚本块)加入如下JS代码:

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检测当前URL是否带哈希片段
    if (window.location.hash) {
        // 提取哈希值,去掉开头的#
        const pageNum = window.location.hash.substring(1);
        // 构造目标URL
        const targetUrl = `${window.location.origin}${window.location.pathname}?p=${pageNum}`;
        // 替换当前历史记录跳转,不会产生多余的回退记录
        window.location.replace(targetUrl);
    }
});

添加后访问/Category/4797/kondicionirovanie#6会自动跳转至/Category/4797/kondicionirovanie?p=6,完全符合你的需求。

方案2:替换为路径格式(如/Category/4797/kondicionirovanie/6)

如果需要把#替换为路径分隔符/,只需要修改JS的URL构造逻辑,再配合后端路由配置即可:

  1. 修改前端JS:
document.addEventListener('DOMContentLoaded', function() {
    if (window.location.hash) {
        const pageNum = window.location.hash.substring(1);
        const targetUrl = `${window.location.origin}${window.location.pathname}/${pageNum}`;
        window.location.replace(targetUrl);
    }
});
  1. 在Program.cs中添加对应路由规则:
app.MapControllerRoute(
    name: "category-paged",
    pattern: "Category/{categoryId:int}/{categorySlug}/{page:int}",
    defaults: new { controller = "Category", action = "Index" });

可选优化

如果需要做SEO优化,建议在跳转时返回301永久重定向状态码:前端捕获哈希后先把哈希值作为查询参数传给后端的重定向接口,后端返回301响应并指定目标地址即可。

内容的提问来源于stack exchange,提问作者Владимир Мирошниченко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:45:11