如何设置ServiceHostingEnvironment.AspNetCompatibilityEnabled = true在code(未配置)的.NET / C#如何设置、ServiceHosti

2023-09-03 09:45:28 作者:じòぴé、離莪冭遙逺

我有一个要求,从访问HttpContext.Current使用,在一个RESTful WCF服务。我知道我能做到这一点通过添加以下配置:

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:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

和使用以下属性在我的服务:

and using the following attribute on my service:

[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Required)]

下面是我的问题,我需要旋服务的一个实例,在code单元测试,所以我不能使用配置文件来指定服务bebaviours等。 此刻我的code样子如下,但尽管淘网我已经无法工作了我如何建立一个ServiceHostingEnvironment类和AspNetCompatibilityEnabled属性设置为true,而无需使用配置,任何人都可以帮忙吗?

Here is my issue, I need to "spin up" an instance of the service in code for unit testing and therefore I cannot use config files to specify service bebaviours etc. At the moment my code looks like follows, but despite scouring the web I have been unable to work out how I set up a ServiceHostingEnvironment class and set the AspNetCompatibilityEnabled property to true without using config, can anyone help?

string serviceUrl = "http://localhost:8082/MyService.svc";

_host = new ServiceHost(typeof(MyService), new Uri[] { new Uri(serviceUrl) });

ServiceEndpoint serviceEndpoint 
    = _host.AddServiceEndpoint(typeof(IMyService), new WebHttpBinding(), string.Empty);

serviceEndpoint.Behaviors.Add(new WebHttpBehavior());

// Here's where I'm stuck, i need something like...
ServiceHostingEnvironmentSection shes = new ServiceHostingEnvironmentSection();
shes.AspNetCompatibilityEnabled = true;
_host.Add(shes);

_host.Open();

任何帮助是提前多少AP preciated和感谢。

Any help is much appreciated and thanks in advance.

推荐答案

考虑分解出明确使用HttpContext.Current的接口后,你可以在单元测试过程存根出。

Consider factoring out the explicit use of HttpContext.Current behind an interface that you can stub out during unit testing.

HttpContext.Current只被定义在WCF服务的一个asp.net web应用程序中托管反正 - 如果有一天你需要承载它作为一个普通的WCF服务,HttpContext.Current是不会用。

HttpContext.Current is only defined when your wcf service is hosted within an asp.net web application anyway - if some day you need to host it as an ordinary wcf service, HttpContext.Current is not going to be available.