使用自定义域名获取当前路径名(JavaScript与C#实现)
解决自定义域名替换默认平台域名的URL生成问题
C# 实现方案
方式1:通过配置文件管理自定义域名(推荐)
这种方式便于后续修改域名,无需改动代码:
- 在项目的Web.config文件中,找到
<appSettings>节点,添加自定义域名配置:
<appSettings> <add key="CustomDomain" value="your-custom-domain.com" /> </appSettings>
- 在业务代码中读取配置,拼接出带自定义域名的完整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
相关产品推荐
相关产品推荐

