在ASP.NET Core RC 1中,我使用以下代码来检索上下文的值(页面的完整地址)。然后我将此值记录在配置中。
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
private IHostingEnvironment CurrentEnvironment { get; set; }
private IHttpContextAccessor HttpContextAccessor { get; set; }
public Startup(IHostingEnvironment env,
IHttpContextAccessor httpContextAccessor)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
CurrentEnvironment = env;
HttpContextAccessor = httpContextAccessor;
}
public void ConfigureServices(IServiceCollection services)
{
...
services.AddOptions();
services.Configure<WebAppSettings>(configuration);
services.Configure<WebAppSettings>(settings =>
{
...
settings.WebRootPath = CurrentEnvironment.WebRootPath;
settings.DomainUrl = HttpContextAccessor.HttpContext.Request.Host.ToUriComponent();
});
}
}
我开始更新ASP.NET Core 1.0项目,但在网站启动期间遇到以下错误:
System.InvalidOperationException 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务,而尝试激活“MyProject.Startup”。
在应用程序启动时如何获取新版本的IHttpContextAccessor?
IHttpContextAccessor
不再默认注册。https://github.com/aspnet/Hosting/issues/793 - DavidG