How to set ServiceHostingEnvironment.AspNetCompatibilityEnabled = true in Code (not in config) .NET/C#

前端 未结 5 1694
南笙
南笙 2021-02-03 11:09

I have a requirement to access the HttpContext.Current from with-in a RESTful WCF service. I know I am able to achieve this by adding the following to config:

&         


        
5条回答
  •  佛祖请我去吃肉
    2021-02-03 11:37

    After digging around with Reflector, I was able to set the AspNetCompatibilityEnabled flag using reflection. This approach has obvious drawbacks, but it did the job for me:

            // get the ServiceHostingEnvironmentSection by calling an internal static method
            var section = (ServiceHostingEnvironmentSection)typeof(ServiceHostingEnvironmentSection).GetMethod("UnsafeGetSection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).Invoke(null, null);
            // set the read-only flag to false so values can be updated
            typeof(ServiceHostingEnvironmentSection).BaseType.BaseType.GetField("_bReadOnly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(section, false);
            // set the AspNetCompatibilityEnabled value
            section.AspNetCompatibilityEnabled = true;
    
            // now one can add a Service Route
            routes.Add(new ServiceRoute("MyRoutePrefix", new ServiceHostFactory(), typeof(MyService)));
    

提交回复
热议问题