我已经阅读了有关此问题的所有其他帖子,并且我确定这不是重复的。
我正在构建要在Startup.cs
类中使用的Razor页面过滤器,我需要访问HttpContext
。 I would normally do this through constructor injection using ASP.NET Core's DI capabilities.我什至在services.AddHttpContextAccessor()
中都有通常的Startup.cs
语句,并在项目的其他地方使用它。
因为我正在建立一个从Razor page filter派生并从IAsyncPageFilter
类创建的Startup.cs
,所以它似乎好像不能注入(因为它是由启动创建的,而不是注入的) 。
这里是Startup.cs
的附加过滤器:
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
options.Filters.Add(new RazorAsyncPageFilter(_logger, Configuration)); <---my filter
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
这是我的过滤器:
public class RazorAsyncPageFilter : IAsyncPageFilter
{
private readonly ILogger _logger;
private readonly IConfiguration _configuration;
public string[] Scopes { get; set; }
public string ScopeKeySection { get; set; }
public RazorAsyncPageFilter(ILogger logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
public async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
{
await Task.CompletedTask;
}
public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
VaultGraphServiceClient.OnMsalUiExceptionEvent += VaultGraphServiceClientOnOnMsalUiExceptionEvent;
await next.Invoke();
}
private void VaultGraphServiceClientOnOnMsalUiExceptionEvent(object sender, MsalUiRequiredException e)
{
_logger.LogInformation($"Triggered authentication exception: {e.Message}");
Scopes = new string[] { _configuration.GetValue<string>(ScopeKeySection) };
var properties = BuildAuthenticationPropertiesForIncrementalConsent(Scopes, e, **I_NEED_CONTEXT_HERE**);
new ChallengeResult(properties);
}
}
请注意从另一个类的事件处理程序触发的方法调用中需要的上下文。我想将HttpContext
传递给过滤器类中的私有方法。
在Startup.cs
中为IHttpContextAccessor _httpContext
定义一个字段,并将其传递给过滤器,但是由于该上下文尚未建立,因此这显然不起作用。
通过其他方法传递上下文。这还需要更多工作,并且充满了warnings about passing it to a background thread。
从我的调用EventHandler
中插入上下文。不幸的是,这是从静态类中调用的,并且据我了解,静态类中没有DI的概念。它是否正确?另外,我正在使用EventHandler
委托,该委托用于传递MsalUiRequiredException
对象,并且只能传递一个对象。也许我可以对event
类型使用不同的处理程序,但是我对事件并不足够了解,无法理解该如何完成。
[我正在考虑创建一个自定义类,以同时容纳MsalUiRequiredException
和HttpContext
,可以在其他地方注入/传递它,但这似乎有点过头了,或者按照上述#2可能是个问题。] >
有什么建议吗?
我已经阅读了有关此问题的所有其他帖子,并且我确定这不是重复的。我正在构建要在Startup.cs类中使用的Razor页面过滤器,并且需要访问HttpContext。我...
添加IHttpContextAccessor
作为构造函数参数