gpt4 book ai didi

c# - 如何在代码(而不是配置).NET/C# 中设置 ServiceHostingEnvironment.AspNetCompatibilityEnabled = true

转载 作者:太空狗 更新时间:2023-10-29 17:58:44 38 4
gpt4 key购买 nike

我需要从 RESTful WCF 服务中访问 HttpContext.Current。我知道我可以通过在配置中添加以下内容来实现这一点:

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />

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

[AspNetCompatibilityRequirements(RequirementsMode 
= AspNetCompatibilityRequirementsMode.Required)]

这是我的问题,我需要在代码中“启动”服务实例以进行单元测试,因此我无法使用配置文件来指定服务行为等。目前我的代码如下所示,但尽管在网上进行了搜索,但我一直无法弄清楚如何在不使用配置的情况下设置 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();

非常感谢任何帮助,并提前致谢。

最佳答案

你完全可以做到这一点,我不知道这些其他答案是关于什么的,但他们离得很远!

只需执行以下操作:

_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();

-- 编辑这将删除现有行为(如果存在),然后添加具有您喜欢的模式的新行为。我的示例将其设置为 .Allowed,但您当然可以将其设置为您想要的模式。

关于c# - 如何在代码(而不是配置).NET/C# 中设置 ServiceHostingEnvironment.AspNetCompatibilityEnabled = true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1721219/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com