Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. Access HttpContext in ASP.NET Core

Access HttpContext in ASP.NET Core

Scheduled Pinned Locked Moved ASP.NET
asp-netcsharpdotnetarchitecturetutorial
18 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • V Vincent Maverick Durano

    ASP.NET Core is all about middleware and DI. In ASP.NET Core, the UrlHelper requires the current action context, and you can acquire that from the ActionContextAccessor. For example in your ConfigureServices method, you can do:

    public void ConfigureServices(IServiceCollection services)
    {
    services.AddMvc();
    services.AddSingleton();
    }

    You can then inject the IActionContextAccessor and use it in your custom helper service:

    public class MyCustomHelper : IMyCustomHelper
    {
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IUrlHelperFactory _urlHelperFactory;

    public MyCustomHelper(IHttpContextAccessor httpContextAccessor, IUrlHelperFactory urlHelperFactory)
    {
    	\_httpContextAccessor = httpContextAccessor;
        \_urlHelperFactory = urlHelperFactory;
    }
    
    public string GetUrl()
    {
    	var context = \_httpContextAccessor.HttpContext;
    	IUrlHelper urlHelper = urlHelperFactory.GetUrlHelper(context);
                //do stuff here
    }
    

    }

    J Offline
    J Offline
    JimFeng
    wrote on last edited by
    #3

    Thanks for your response. I'm new to ASP.NET Core and still have following questions: 1. Where should I put ConfigureServices method? 2. My current MVC5 custom helper like following: public static class HtmlHelperExt { public static IHtmlString CHGridTable(this HtmlHelper htmlHelper, DataTable dt, object htmlAttributes = null) { UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); string urlEdit = url.RouteUrl("Default"); ...... } ......//many other custom helpers } How can I inject the IActionContextAccessor and use it in my custom helper CHGridTable and other helpers? 3. How can I use the ContextAccessor to get info for the code lines below: UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); string urlEdit = url.RouteUrl("Default");

    V Richard DeemingR 2 Replies Last reply
    0
    • J JimFeng

      Thanks for your response. I'm new to ASP.NET Core and still have following questions: 1. Where should I put ConfigureServices method? 2. My current MVC5 custom helper like following: public static class HtmlHelperExt { public static IHtmlString CHGridTable(this HtmlHelper htmlHelper, DataTable dt, object htmlAttributes = null) { UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); string urlEdit = url.RouteUrl("Default"); ...... } ......//many other custom helpers } How can I inject the IActionContextAccessor and use it in my custom helper CHGridTable and other helpers? 3. How can I use the ContextAccessor to get info for the code lines below: UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); string urlEdit = url.RouteUrl("Default");

      V Offline
      V Offline
      Vincent Maverick Durano
      wrote on last edited by
      #4

      JimFeng wrote:

      I'm new to ASP.NET Core and still have following questions:

      1. Where should I put ConfigureServices method?

      Configuring services should be placed inside startup.cs. For more details, see: ASP.NET Core fundamentals | Microsoft Docs[^]

      JimFeng wrote:

      How can I inject the IActionContextAccessor and use it in my custom helper CHGridTable and other helpers?

      While it may be possible, I would still recommend you to convert your static/extension class into a service whose concrete implementation would use the IHttpContextAccessor as a dependency that can be injected via its constructor just like what I've showed you on my first reply. If you still want to follow the static class approach then you could try this:

      public static class HtmlHelperExt{
      private static IHttpContextAccessor _httpContextAccessor;
      private static IUrlHelperFactory _urlHelperFactory;
      public static void SetHttpContextAccessor(IHttpContextAccessor accessor, IUrlHelperFactory urlHelperFactory) {
      _httpContextAccessor = accessor;
      _urlHelperFactory = urlHelperFactory;
      }

      public static IHtmlString CHGridTable(this HtmlHelper htmlHelper, DataTable dt, object htmlAttributes = null)
      {
              var urlHelper = \_urlHelperFactory.GetUrlHelper(\_httpContextAccessor.HttpContext);
              string urlEdit = urlHelper.RouteUrl("Default");
              //rest of the stuff here
      }
      

      }

      In the Startup.ConfigureServices method you can call services.BuildServiceProvider() to get the IServiceProvider to resolve the type you seek. For example:

      public void ConfigureServices(IServiceCollection service) {

      services.AddMvc();
      
      //this would have been done by the framework any way after this method call;
      //in this case you call the BuildServiceProvider manually to be able to use it
      var serviceProvider = services.BuildServiceProvider();
      
      //here is where you set you accessor and url helper factory
      var accessor = serviceProvider.GetService
      
      J 1 Reply Last reply
      0
      • V Vincent Maverick Durano

        JimFeng wrote:

        I'm new to ASP.NET Core and still have following questions:

        1. Where should I put ConfigureServices method?

        Configuring services should be placed inside startup.cs. For more details, see: ASP.NET Core fundamentals | Microsoft Docs[^]

        JimFeng wrote:

        How can I inject the IActionContextAccessor and use it in my custom helper CHGridTable and other helpers?

        While it may be possible, I would still recommend you to convert your static/extension class into a service whose concrete implementation would use the IHttpContextAccessor as a dependency that can be injected via its constructor just like what I've showed you on my first reply. If you still want to follow the static class approach then you could try this:

        public static class HtmlHelperExt{
        private static IHttpContextAccessor _httpContextAccessor;
        private static IUrlHelperFactory _urlHelperFactory;
        public static void SetHttpContextAccessor(IHttpContextAccessor accessor, IUrlHelperFactory urlHelperFactory) {
        _httpContextAccessor = accessor;
        _urlHelperFactory = urlHelperFactory;
        }

        public static IHtmlString CHGridTable(this HtmlHelper htmlHelper, DataTable dt, object htmlAttributes = null)
        {
                var urlHelper = \_urlHelperFactory.GetUrlHelper(\_httpContextAccessor.HttpContext);
                string urlEdit = urlHelper.RouteUrl("Default");
                //rest of the stuff here
        }
        

        }

        In the Startup.ConfigureServices method you can call services.BuildServiceProvider() to get the IServiceProvider to resolve the type you seek. For example:

        public void ConfigureServices(IServiceCollection service) {

        services.AddMvc();
        
        //this would have been done by the framework any way after this method call;
        //in this case you call the BuildServiceProvider manually to be able to use it
        var serviceProvider = services.BuildServiceProvider();
        
        //here is where you set you accessor and url helper factory
        var accessor = serviceProvider.GetService
        
        J Offline
        J Offline
        JimFeng
        wrote on last edited by
        #5

        Thanks again for your patient. when I code following: var urlHelper = _urlHelperFactory.GetUrlHelper(_httpContextAccessor.HttpContext); and got the following error: Argument 1: cannot convert from 'Microsoft.AspNetCore.Http.HttpContext' to 'Microsoft.AspNetCore.Mvc.ActionContext' the error was caused by argument: _httpContextAccessor.HttpContext

        V 1 Reply Last reply
        0
        • J JimFeng

          Thanks for your response. I'm new to ASP.NET Core and still have following questions: 1. Where should I put ConfigureServices method? 2. My current MVC5 custom helper like following: public static class HtmlHelperExt { public static IHtmlString CHGridTable(this HtmlHelper htmlHelper, DataTable dt, object htmlAttributes = null) { UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); string urlEdit = url.RouteUrl("Default"); ...... } ......//many other custom helpers } How can I inject the IActionContextAccessor and use it in my custom helper CHGridTable and other helpers? 3. How can I use the ContextAccessor to get info for the code lines below: UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); string urlEdit = url.RouteUrl("Default");

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #6

          asp.net core - how to get IUrlHelper from inside Html helper - Stack Overflow[^] Correcting the typo in that answer gives:

          public static IHtmlContent CHGridTable<TModel>(this IHtmlHelper<TModel> htmlHelper, DataTable dt, object htmlAttributes = null)
          {
          var urlHelperFactory = (IUrlHelperFactory)htmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelperFactory));
          var urlHelper = urlHelperFactory.GetUrlHelper(htmlHelper.ViewContext);
          string urlEdit = url.RouteUrl("Default");
          ...
          }

          You might also want to consider whether a custom tag helper might be a better choice for what you're trying to do: Tag Helpers in ASP.NET Core | Microsoft Docs[^]


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          J 1 Reply Last reply
          0
          • J JimFeng

            Thanks again for your patient. when I code following: var urlHelper = _urlHelperFactory.GetUrlHelper(_httpContextAccessor.HttpContext); and got the following error: Argument 1: cannot convert from 'Microsoft.AspNetCore.Http.HttpContext' to 'Microsoft.AspNetCore.Mvc.ActionContext' the error was caused by argument: _httpContextAccessor.HttpContext

            V Offline
            V Offline
            Vincent Maverick Durano
            wrote on last edited by
            #7

            Hmm.. it's really hard to test it out without a dev machine. Anyway instead of passing IHttpContextAccessor, try to pass the IActionContextAccessor instead. For example in your Helper class, you can do:

            private static IActionContextAccessor \_actionContextAccessor;
            private static IUrlHelperFactory \_urlHelperFactory;
            public static void SetHttpContextAccessor(IActionContextAccessor accessor, IUrlHelperFactory urlHelperFactory) {
                \_actionContextAccessor = accessor;
                \_urlHelperFactory = urlHelperFactory;
            }
            

            then you can do:

            var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);

            and finally, configure the IActionContextAccessor in Startup.ConfigureServices method:

            var accessor = serviceProvider.GetService()
            var userHelperFactory = serviceProvider.GetService()
            HtmlHelperExt.SetHttpContextAccessor(accessor,userHelperFactory);
            

            You could also try what's suggested by Richard.

            1 Reply Last reply
            0
            • Richard DeemingR Richard Deeming

              asp.net core - how to get IUrlHelper from inside Html helper - Stack Overflow[^] Correcting the typo in that answer gives:

              public static IHtmlContent CHGridTable<TModel>(this IHtmlHelper<TModel> htmlHelper, DataTable dt, object htmlAttributes = null)
              {
              var urlHelperFactory = (IUrlHelperFactory)htmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelperFactory));
              var urlHelper = urlHelperFactory.GetUrlHelper(htmlHelper.ViewContext);
              string urlEdit = url.RouteUrl("Default");
              ...
              }

              You might also want to consider whether a custom tag helper might be a better choice for what you're trying to do: Tag Helpers in ASP.NET Core | Microsoft Docs[^]


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              J Offline
              J Offline
              JimFeng
              wrote on last edited by
              #8

              Thanks, I corrected error in my custom helper, but when I call the helper from views as following: @HtmlHelperExt.CHGridTable(Model, new { tablename = "tblTest", defaultcolsort = "3" }) and got following error: Error CS0411 The type arguments for method 'HtmlHelperExt.CHGridTable(HtmlHelper, DataTable, object)' cannot be inferred from the usage. Try specifying the type arguments explicitly. The call on MVC5 works file, How can I use the custom helper on view of Core Web Application (MVC6): The custom helper code as following: public static IHtmlContent CHGridTable(this HtmlHelper htmlHelper, DataTable dt, object htmlAttributes = null) { var urlHelperFactory = (IUrlHelperFactory)htmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelperFactory)); var url = urlHelperFactory.GetUrlHelper(htmlHelper.ViewContext); ...... return new HtmlString(tbBtnAdd.ToString() + tbGridTable.ToString() + script.ToString()); }

              Richard DeemingR 1 Reply Last reply
              0
              • J JimFeng

                Thanks, I corrected error in my custom helper, but when I call the helper from views as following: @HtmlHelperExt.CHGridTable(Model, new { tablename = "tblTest", defaultcolsort = "3" }) and got following error: Error CS0411 The type arguments for method 'HtmlHelperExt.CHGridTable(HtmlHelper, DataTable, object)' cannot be inferred from the usage. Try specifying the type arguments explicitly. The call on MVC5 works file, How can I use the custom helper on view of Core Web Application (MVC6): The custom helper code as following: public static IHtmlContent CHGridTable(this HtmlHelper htmlHelper, DataTable dt, object htmlAttributes = null) { var urlHelperFactory = (IUrlHelperFactory)htmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelperFactory)); var url = urlHelperFactory.GetUrlHelper(htmlHelper.ViewContext); ...... return new HtmlString(tbBtnAdd.ToString() + tbGridTable.ToString() + script.ToString()); }

                Richard DeemingR Offline
                Richard DeemingR Offline
                Richard Deeming
                wrote on last edited by
                #9

                JimFeng wrote:

                @HtmlHelperExt.CHGridTable(Model, new { tablename = "tblTest", defaultcolsort = "3" })

                That should probably be:

                @Html.CHGridTable(Model, new { tablename = "tblTest", defaultcolsort = "3" })

                You need to call it as an extension method on the IHtmlHelper instance, not call the static method directly.


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                J 1 Reply Last reply
                0
                • Richard DeemingR Richard Deeming

                  JimFeng wrote:

                  @HtmlHelperExt.CHGridTable(Model, new { tablename = "tblTest", defaultcolsort = "3" })

                  That should probably be:

                  @Html.CHGridTable(Model, new { tablename = "tblTest", defaultcolsort = "3" })

                  You need to call it as an extension method on the IHtmlHelper instance, not call the static method directly.


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  J Offline
                  J Offline
                  JimFeng
                  wrote on last edited by
                  #10

                  @Html.CHGridTable(......) works on MVC5 but not ASP.NET Core MVC.

                  Richard DeemingR 1 Reply Last reply
                  0
                  • J JimFeng

                    @Html.CHGridTable(......) works on MVC5 but not ASP.NET Core MVC.

                    Richard DeemingR Offline
                    Richard DeemingR Offline
                    Richard Deeming
                    wrote on last edited by
                    #11

                    Have you imported the tag helpers from your assembly? /Views/_ViewImports.cshtml:

                    @addTagHelper *, YourAssemblyNameHere

                    Managing Tag Helper scope | Tag Helpers in ASP.NET Core | Microsoft Docs[^]


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                    J 2 Replies Last reply
                    0
                    • Richard DeemingR Richard Deeming

                      Have you imported the tag helpers from your assembly? /Views/_ViewImports.cshtml:

                      @addTagHelper *, YourAssemblyNameHere

                      Managing Tag Helper scope | Tag Helpers in ASP.NET Core | Microsoft Docs[^]


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      J Offline
                      J Offline
                      JimFeng
                      wrote on last edited by
                      #12

                      I added @addTagHelper *, HtmlHelperExt in _ViewImports.cshtml file but still got error: Error: CS1061 'IHtmlHelper' does not contain a definition for 'CHDropdownMenu' and no accessible extension method 'CHDropdownMenu' accepting a first argument of type 'IHtmlHelper' could be found (are you missing a using directive or an assembly reference?) on the View page like this (the same as on MVC 5): @model System.Data.DataSet @using HtmlHelperExt; ...... @Html.CHDropdownMenu(Model, "mnuSample1", new { MenuOpenType = "Hover" }) ...... My Custom helper like this: namespace HtmlHelperExt { public static class HtmlHelperExt { public static IHtmlContent CHDropdownMenu(this HtmlHelper htmlHelper, DataSet ds, string divID, object htmlAttributes = null) { ...... return new HtmlString(tbDiv_Menu.ToString()); } } }

                      Richard DeemingR 1 Reply Last reply
                      0
                      • J JimFeng

                        I added @addTagHelper *, HtmlHelperExt in _ViewImports.cshtml file but still got error: Error: CS1061 'IHtmlHelper' does not contain a definition for 'CHDropdownMenu' and no accessible extension method 'CHDropdownMenu' accepting a first argument of type 'IHtmlHelper' could be found (are you missing a using directive or an assembly reference?) on the View page like this (the same as on MVC 5): @model System.Data.DataSet @using HtmlHelperExt; ...... @Html.CHDropdownMenu(Model, "mnuSample1", new { MenuOpenType = "Hover" }) ...... My Custom helper like this: namespace HtmlHelperExt { public static class HtmlHelperExt { public static IHtmlContent CHDropdownMenu(this HtmlHelper htmlHelper, DataSet ds, string divID, object htmlAttributes = null) { ...... return new HtmlString(tbDiv_Menu.ToString()); } } }

                        Richard DeemingR Offline
                        Richard DeemingR Offline
                        Richard Deeming
                        wrote on last edited by
                        #13

                        JimFeng wrote:

                        IHtmlHelper<dataset>' does not contain a definition for 'CHDropdownMenu'

                        CHDropdownMenu<tmodel>(this HtmlHelper<tmodel> htmlHelper,

                        You need to declare the helper method as an extension method against the IHtmlHelper interface, not the HtmlHelper class.

                        public static IHtmlContent CHDropdownMenu<TModel>(this IHtmlHelper<TModel> htmlHelper, ...

                        IHtmlHelper Interface (Microsoft.AspNetCore.Mvc.Rendering) | Microsoft Docs[^]


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                        1 Reply Last reply
                        0
                        • Richard DeemingR Richard Deeming

                          Have you imported the tag helpers from your assembly? /Views/_ViewImports.cshtml:

                          @addTagHelper *, YourAssemblyNameHere

                          Managing Tag Helper scope | Tag Helpers in ASP.NET Core | Microsoft Docs[^]


                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                          J Offline
                          J Offline
                          JimFeng
                          wrote on last edited by
                          #14

                          My assembly is a custom HtmlHelper NOT TagHelper.

                          Richard DeemingR 1 Reply Last reply
                          0
                          • J JimFeng

                            My assembly is a custom HtmlHelper NOT TagHelper.

                            Richard DeemingR Offline
                            Richard DeemingR Offline
                            Richard Deeming
                            wrote on last edited by
                            #15

                            Yes, of course. :doh: You'll want @using statements for your namespace, rather than @addTagHelper statements. Still in the _ViewImports.cshml file, though.

                            @using HtmlHelperExt


                            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                            "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                            J 1 Reply Last reply
                            0
                            • Richard DeemingR Richard Deeming

                              Yes, of course. :doh: You'll want @using statements for your namespace, rather than @addTagHelper statements. Still in the _ViewImports.cshml file, though.

                              @using HtmlHelperExt


                              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                              J Offline
                              J Offline
                              JimFeng
                              wrote on last edited by
                              #16

                              @using HtmlHelperExt is already in the _ViewImports.cshml, but got the same error.

                              Richard DeemingR 1 Reply Last reply
                              0
                              • J JimFeng

                                @using HtmlHelperExt is already in the _ViewImports.cshml, but got the same error.

                                Richard DeemingR Offline
                                Richard DeemingR Offline
                                Richard Deeming
                                wrote on last edited by
                                #17

                                Did you change the first parameter of the extension method, as I suggested yesterday?


                                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                J 1 Reply Last reply
                                0
                                • Richard DeemingR Richard Deeming

                                  Did you change the first parameter of the extension method, as I suggested yesterday?


                                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                  J Offline
                                  J Offline
                                  JimFeng
                                  wrote on last edited by
                                  #18

                                  Thank you Rick, after I changed the parm type, and the helper works in my ASP.NET Core 2.1 MVC app.

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups