在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; …Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何访问ASP.NET控制器之外的当前登录用户名.
例如,我试图这样做:
设置跟踪实体的跟踪DbContext.
这是我的,ApplicationDbContext但我一直收到错误的说法_httpContextAccessor是null:
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor = httpContextAccessor;
}
Run Code Online (Sandbox Code Playgroud) c# entity-framework asp.net-core-mvc asp.net-core asp.net-core-1.0
我有静态助手类
public static class Current
{
public static string Host
{
get { return "httpContextAccessor here"; }
}
}
Run Code Online (Sandbox Code Playgroud)
如何在Host属性中访问当前的HttpContext?
在 ASP.NET Core 中,我有一个在 DI 中注册为作用域的服务。我可以访问该服务中的 HTTP 上下文而不使用IHttpContextAccessor它的开销吗?
我收到这样的错误:
无法使用单例“MyNamespace.IMyCustomThing”中的范围服务“Microsoft.AspNetCore.Http.IHttpContextAccessor”
我很困惑,因为我是IHttpContextAccessor通过打电话注册的services.AddHttpContextAccessor()。AddHttpContextAccessor 的代码在这里。相关部分是这样的:
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)
IHttpContextAccessor 注册为单例。为什么 ASP.Net Core 认为它是一个范围服务?
注意:如果相关,IMyCustomThing请使用 来IHttpContextAccessor查看是否存在当前HttpContext,如果不存在则采取其他操作。