当在 launchSettings.json 中为本地开发指定主机名时
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://mysite.local:6200;http://mysite.local:5200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
这会导致日志不写出主机名:
[10:28:36 INF] 现在收听:https://[::]:6100
[10:28:36 INF] 现在收听:http://[::]:5100
如果我恢复到本地主机,我会得到:
[10:28:36 INF] 现在正在收听:https://localhost:6100
[10:28:36 INF] 现在收听:http://locahost:5100
是否可以注销自定义域?
默认情况下,Kestrel 使用其侦听的实际 IP 地址来记录其绑定。因此日志不会显示域名 (mysite.local),它会记录 IP 地址格式(对于 IPv6 为
[::]
,对于 IPv4 为 127.0.0.1
)。
记录域名的解决方法是创建自定义中间件,如下所示:
public class LogDomainMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<LogDomainMiddleware> _logger;
public LogDomainMiddleware(RequestDelegate next, ILogger<LogDomainMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var hostName = context.Request.Host.Value;
_logger.LogInformation($"Request received for domain: {hostName}");
await _next(context);
}
}
在Program.cs中注册中间件:
app.UseMiddleware<LogDomainMiddleware>();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();