In my own DI I am trying to fork code based on whether the current request is executing in the context of an anoymous request or not. I guessed the easiest way would be to infer the type of the current controller and see if it was a subtype of our own anonymous api controller:
public bool InAnonymousContext() {
var anonymousContext = false;
if (_actionContextAccessor?.ActionContext != null)
{
var controllerContext = new ControllerContext(_actionContextAccessor.ActionContext);
var type = controllerContext.ActionDescriptor.ControllerTypeInfo?.GetType();
anonymousContext = type.IsSubclassOf(typeof(AbstractAnonymousApiController)) ?? false;
}
return anonymousContext;
}
but I've made a wrong assumption that IActionContextAccessor
would be available to me from DI.
Any ideas how to go about this?
CodePudding user response:
Found meta data on the HttpContext
via DI & IHttpContextAccessor
var ctx = sp.GetRequiredService<IHttpContextAccessor>();
var action = ctx.HttpContext?.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>();
var type = action?.ControllerTypeInfo.AsType();
if (type != null && type.IsSubclassOf(typeof(AbstractAnonymousApiController)))
return null;