How do I access the Request object from a Tag Helper
Asked Answered
C

1

8

I am developing a Tag Helper in ASP.NET Core (RC2), and when rendering the Tag Helper I need to access the Request object as I need to figure out what the URL of the request is.

So it seems that in ASP.NET Core the correct way to access the Request object is from the HttpContext, and to obtain the HttpContext I need to inject IHttpContextAccessor into my Tag Helper.

So I tried that but the following exception gets thrown at runtime:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Auth0.AspNetCore.Mvc.TagHelpers.LockTagHelper'.

Is there any reason I cannot inject IHttpContextAccessor into my Tag Helper?

Also, is there perhaps another way to access the Request object inside a Tag Helper?

Edit

It seems the issue is that since the latest Release Candidates you have to manually configure the DI to handle IHttpContextAccessor. So in ConfigureServices you have to make a call to

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

I believe in earlier betas this was automatically configured...

Problem is that this is a library, and I would prefer not to expect users to configure this in their application for my library to work correctly, so any other, more reliable way to access the Request object will still be appreciated :)

Cellaret answered 25/5, 2016 at 12:54 Comment(4)
same question answered here #37371764Wrinkle
@JoeAudette Thanks I also just noticed this. I edited my question to state that this is not a preferable solution as I now expect my users to wire up DI just to use my Tag Helper. Would still like to see if there is another more reliable way to access the Request object without expecting the user to wire things upCellaret
your question says rc1, but afaik this was not needed in rc1, it changed in rc2, I agree it is such a commonly used thing they should have kept that registered by defaultWrinkle
Aaargh. yes it is RC2. Will updateCellaret
C
10

As per Pranav's response in regards to issue #4744 regarding the same topic on aspnet/mvc at GitHub:

You can add a property of type ViewContext decorated with ViewContextAttribute to your tag helper. This will get initialized to the ViewContext of the executing page:

[ViewContext]
public ViewContext ViewContext { get; set; }

private HttpRequest Request => ViewContext.HttpContext.Request;
Cellaret answered 25/5, 2016 at 13:48 Comment(1)
Also, it is better to set both [ViewContext, HtmlAttributeNotBound] attributes. the [HtmlAttributeNotBound] would enable you to opt-out of TagHelper binding (we don't want to set this property via tag helper attributes in the View).Fluctuation

© 2022 - 2024 — McMap. All rights reserved.