在 ASP.NET 中获取网站域名有多种方法,具体取决于你使用的 ASP.NET 版本(Web Forms, MVC, Core)以及你需要获取域名的具体场景(是当前请求的域名,还是配置中固定的域名)。
下面我将分门别类地介绍最常用和最可靠的方法。
获取当前请求的域名(最常见)
这是最常见的需求,即在处理用户请求时,动态获取访问网站的域名,用于生成绝对 URL、重定向或记录日志等。
ASP.NET Core (推荐)
在 ASP.NET Core 中,通过 HttpContext 对象获取信息是标准做法。
在 Razor Pages (.cshtml) 或 MVC View (.cshtml) 中:
@* 在 Razor Page Model 中 *@
@page
@model YourModel
@{
var host = Context.Request.Host; // 类型: HostString
var scheme = Context.Request.Scheme; // "http" 或 "https"
var baseUrl = $"{scheme}://{host}";
}
<!DOCTYPE html>
<html>
<head>域名信息</title>
</head>
<body>
<h1>当前域名信息</h1>
<p>Host: @host.Host (@host.Port.HasValue ? ":" + host.Port.Value : "")</p>
<p>Scheme: @scheme</p>
<p>完整 Base URL: @baseUrl</p>
</body>
</html>
在 Controller 或 Page Model 的 C# 代码中:
public class MyController : Controller
{
public IActionResult Index()
{
// 获取 HostString 对象,包含主机名和端口
var host = HttpContext.Request.Host;
// 获取协议 (http 或 https)
var scheme = HttpContext.Request.Scheme;
// 获取原始的 URL 字符串
var originalUrl = HttpContext.Request.GetDisplayUrl();
// 构建一个绝对 URL
var absoluteUrl = Url.Action("Index", "Home", null, scheme); // https://localhost:5001/Home
// 将信息传递给 View
ViewBag.Host = host;
ViewBag.Scheme = scheme;
ViewBag.AbsoluteUrl = absoluteUrl;
return View();
}
}
关键对象:

HttpContext.Request.Host: 包含Host(字符串) 和Port(可空 int) 属性。HttpContext.Request.Scheme: 获取协议,通常是 "http" 或 "https"。
ASP.NET Web Forms / MVC (旧版)
在传统的 ASP.NET 中,主要通过 HttpRequest 对象来获取。
在 Page (.aspx) 或 Controller 中:
// 在 Page_Load 事件或 Controller Action 中
protected void Page_Load(object sender, EventArgs e)
{
// 方法一:获取原始 URL (包含路径和查询字符串)
// http://www.example.com:8080/page.aspx?id=123
string originalUrl = Request.Url.AbsoluteUri;
string pathAndQuery = Request.Url.PathAndQuery; // /page.aspx?id=123
// 方法二:只获取主机名和端口
// www.example.com:8080
string authority = Request.Url.Authority;
// 方法三:只获取主机名
// www.example.com
string host = Request.Url.Host;
// 方法四:获取协议
// http 或 https
string scheme = Request.Url.Scheme;
// 方法五:获取完整的基础 URL (不含路径)
// http://www.example.com:8080
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
// 在页面上显示
lblHost.Text = host;
lblScheme.Text = scheme;
lblBaseUrl.Text = baseUrl;
}
关键对象:
Request.Url: 这是一个System.Uri对象,包含了请求 URL 的所有信息。
从配置文件中获取域名
如果你有一个固定的域名,或者需要一个开发/测试/生产环境可配置的域名,最佳实践是将其存储在配置文件中。

ASP.NET Core (appsettings.json)
这是现代 ASP.NET Core 推荐的方式。
appsettings.json 文件:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AppSettings": {
"DomainName": "https://www.your-production-domain.com"
}
}
在 C# 代码中读取:
// 在 Startup.cs 或 Program.cs 中注册服务
// builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// 在 Controller 或 Service 中通过依赖注入获取
public class MyController : Controller
{
private readonly AppSettings _appSettings;
public MyController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
public IActionResult Index()
{
string domainFromConfig = _appSettings.DomainName;
// 使用 domainFromConfig ...
return Content($"配置中的域名: {domainFromConfig}");
}
}
// 需要创建一个对应的配置模型类
public class AppSettings
{
public string DomainName { get; set; }
}
ASP.NET Web Forms (Web.config)
在旧版 ASP.NET 中,通常使用 <appSettings> 节。

Web.config 文件:
<configuration>
<appSettings>
<add key="AppDomain" value="https://www.your-production-domain.com" />
</appSettings>
...
</configuration>
在 C# 代码中读取:
// 在 Page_Load 或 Controller 中 string domainFromConfig = ConfigurationManager.AppSettings["AppDomain"]; // 使用 domainFromConfig ...
获取客户端的原始主机头(用于反向代理场景)
在某些情况下,特别是网站部署在反向代理(如 Nginx, IIS ARR)后面时,Request.Host 或 Request.Url.Host 获取到的是代理服务器的主机名,而不是真实的客户端请求域名,这时需要读取 X-Forwarded-Host 请求头。
在 ASP.NET Core 中处理:
ASP.NET Core 默认会配置一些中间件来处理这些标准头,但如果需要手动处理,或者自定义逻辑,可以这样做:
// 在 Controller 或 Service 中
public string GetRealHost(HttpContext context)
{
// 优先检查 X-Forwarded-Host 头
var forwardedHost = context.Request.Headers["X-Forwarded-Host"].FirstOrDefault();
if (!string.IsNullOrEmpty(forwardedHost))
{
return forwardedHost;
}
// 如果没有,则回退到标准的 Host
return context.Request.Host.Host;
}
// 使用示例
public IActionResult Index()
{
string realHost = GetRealHost(HttpContext);
return Content($"真实客户端请求的主机名: {realHost}");
}
在 ASP.NET Web Forms 中处理:
string realHost = Request.Headers["X-Forwarded-Host"];
if (string.IsNullOrEmpty(realHost))
{
realHost = Request.Url.Host;
}
总结与推荐
| 场景 | 推荐方法 | 备注 |
|---|---|---|
| 获取当前请求的域名 | ASP.NET Core: HttpContext.Request.HostASP.NET Web Forms: Request.Url.Host |
这是最直接、最常用的方法。 |
| 生成绝对 URL | ASP.NET Core: Url.Action("Action", "Controller", null, "https")ASP.NET Web Forms: Page.ResolveUrl("~/path") + 构建域名 |
使用框架内置的辅助方法,能更好地处理路由和区域。 |
| 配置固定域名 | ASP.NET Core: appsettings.json + IOptions<T>ASP.NET Web Forms: Web.config + ConfigurationManager.AppSettings |
将配置与代码分离,便于在不同环境(开发、测试、生产)间切换。 |
| 反向代理环境 | 读取 X-Forwarded-Host 请求头 |
确保获取到的是真实客户端请求的域名,而不是代理服务器的。 |
对于新项目,强烈推荐使用 ASP.NET Core,其 HttpContext 模型更加清晰和强大。
