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

使用自定义域名获取当前路径名(JavaScript与C#实现)

解决自定义域名替换默认平台域名的URL生成问题

C# 实现方案

方式1:通过配置文件管理自定义域名(推荐)

这种方式便于后续修改域名,无需改动代码:

  1. 在项目的Web.config文件中,找到<appSettings>节点,添加自定义域名配置:
<appSettings>
  <add key="CustomDomain" value="your-custom-domain.com" />
</appSettings>
  1. 在业务代码中读取配置,拼接出带自定义域名的完整URL:
// 读取配置文件中的自定义域名
string customDomain = System.Configuration.ConfigurationManager.AppSettings["CustomDomain"];
// 获取当前请求的协议(http/https)
string scheme = HttpContext.Current.Request.Url.Scheme;
// 获取当前请求的路径和查询参数
string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
// 拼接完整URL
string fullCustomUrl = $"{scheme}://{customDomain}{pathAndQuery}";

验证方式:可通过Fiddler抓包查看接口返回或请求中的URL,也可在代码中输出日志确认结果。

方式2:硬编码自定义域名(仅临时测试使用)

如果只是临时验证效果,可直接在代码中指定自定义域名:

string customDomain = "your-custom-domain.com";
string scheme = HttpContext.Current.Request.Url.Scheme;
string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
string fullCustomUrl = $"{scheme}://{customDomain}{pathAndQuery}";

JavaScript 实现方案

方式1:前端直接替换域名

若前端已知自定义域名,可直接替换当前页面的域名部分:

const customDomain = 'your-custom-domain.com';
// 获取当前页面的协议(http:/https:)
const protocol = window.location.protocol;
// 获取当前页面的路径和查询参数
const pathAndQuery = window.location.pathname + window.location.search;
// 拼接完整URL
const fullCustomUrl = `${protocol}//${customDomain}${pathAndQuery}`;
console.log(fullCustomUrl);

验证方式:打开浏览器开发者工具(按F12),切换到Console面板即可查看生成的URL;也可通过Network面板查看前端请求中使用的URL。

方式2:从后端注入自定义域名(更灵活)

如果自定义域名需要从后端统一管理,可在页面渲染时将域名注入到前端:

<script>
// 从后端配置中获取自定义域名(以ASP.NET Razor视图为例)
const customDomain = '@System.Configuration.ConfigurationManager.AppSettings["CustomDomain"]';
const protocol = window.location.protocol;
const pathAndQuery = window.location.pathname + window.location.search;
const fullCustomUrl = `${protocol}//${customDomain}${pathAndQuery}`;
console.log(fullCustomUrl);
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:00:28