我需要从RESTful WCF服务中使用来访问HttpContext.Current.我知道我可以通过在config中添加以下内容来实现这一目的:
<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />
Run Code Online (Sandbox Code Playgroud)
并在我的服务上使用以下属性:
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Required)]
Run Code Online (Sandbox Code Playgroud)
这是我的问题,我需要在代码中"旋转"一个服务实例进行单元测试,因此我不能使用配置文件来指定服务bebaviours等.目前我的代码看起来如下,但尽管在网上搜索我我一直无法弄清楚如何设置ServiceHostingEnvironment类并在不使用配置的情况下将AspNetCompatibilityEnabled属性设置为true,有人可以帮忙吗?
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();
Run Code Online (Sandbox Code Playgroud)
任何帮助都非常感谢,并提前感谢.
你完全可以做到这一点,我不知道这些其他答案是关于什么的,但它们离我们很远!
只需执行以下操作:
_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();
Run Code Online (Sandbox Code Playgroud)
-- 编辑 这将删除现有行为(如果存在),然后添加具有您喜欢的模式的新行为。我的示例将其设置为 .Allowed,但您当然可以将其设置为您想要的模式。
小智 -3
考虑将 HttpContext.Current 的显式使用排除在接口后面,您可以在单元测试期间将其存根掉。
无论如何,仅当您的 wcf 服务托管在 asp.net Web 应用程序中时才定义 HttpContext.Current - 如果有一天您需要将其托管为普通的 wcf 服务,则 HttpContext.Current 将不可用。
| 归档时间: |
|
| 查看次数: |
13716 次 |
| 最近记录: |