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

前端 未结 5 1686
南笙
南笙 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:41

    You can totally do this, I don't know what these other answers are about, but they are way off!

    Just do something like:

    _host = new ServiceHost(...);
    // Remove existing behavior as it is readOnly
    for (int i = 0; i < _host.Description.Behaviors.Count; i++)
    {
        if (_host.Description.Behaviors[i] is AspNetCompatibilityRequirementsAttribute)
        {
          _host.Description.Behaviors.RemoveAt(i);
          break;
        }
    }
    // Replace behavior with one that is configured the way you desire.
    _host.Description.Behaviors.Add(new AspNetCompatibilityRequirementsAttribute { RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed });
    _host.Open();
    

    -- Edit This removes the existing behavior if it exists, and then adds a new behavior that has the mode you prefer. My example sets it to .Allowed, but you could of course set it to the mode you desire.

提交回复
热议问题