Mvc: Accessing the Request from a Tag Helper

Created on 25 May 2016  路  6Comments  路  Source: aspnet/Mvc

I there any way to access the Request object from a Tag Helper?

question

All 6 comments

@jerriep, 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:

``` C#
[ViewContext]
public ViewContext ViewContext { get; set; }

private HttpRequest Request => ViewContext.HttpContext.Request;
```

Oh sweet, thanks Pranav!

Is there somewhere i can find a list of attributes i can decorate with for things like this?

@danroth27 is this on the docs website? Here's a list of some of the attributes used to DI in \ inject context specific types

  • ControllerContextAttribute - injects a ControllerContext in a controller
  • ViewDataDictionaryAttribute - Inject ViewDataDictionary in a controller
  • FromServicesAttribute - Model binds a service (used to decorate action parameters or in model bound types)
  • ViewContextAttribute - Inject ViewContext in a tag helper
  • ViewComponentContextAttribute - Inject ViewComponentContext in a tag helper
  • RazorInjectAttribute - injects a service in a Razor page (Code behind for @inject)

@Rick-Anderson We have multiple topics that cover DI in MVC:

[FromServices] is covered, but I don't think the other attributes you listed are.

Added https://github.com/aspnet/Docs/issues/1323 to track.

Thanks a lot for the info and links :)

Was this page helpful?
0 / 5 - 0 ratings