2

我在 Web 应用程序中使用自托管(以编程方式托管)WCF 服务。我将[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]属性放置在 SampleService 类中,并将<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false"/>元素放置在部分的 Web.config 中system.serviceModel。我使用下一个代码在 Application_Start 方法中的 Global.asax 中托管我的 WCF 服务:

protected void Application_Start(object sender, EventArgs e)
{
  var serviceType = typeof (SampleService);
  var serviceInterfaceType = typeof(ISampleService);
  var baseAddresses = new Uri(@"https://localhost:443/SilverWIF.WEB/SampleService");
  var serviceHost = new ServiceHost(serviceType, baseAddresses);
  var smb = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
  if (smb == null)
  {
        smb = new ServiceMetadataBehavior { HttpsGetEnabled = true };
        serviceHost.Description.Behaviors.Add(smb);
  }
  else smb.HttpsGetEnabled = true;

  var sdb = serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
  if (sdb == null)
  {
        sdb = new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true };
        serviceHost.Description.Behaviors.Add(sdb);
  }
  else sdb.IncludeExceptionDetailInFaults = true;

  serviceHost.Description.Endpoints.Clear();
  serviceHost.AddServiceEndpoint(serviceInterfaceType, _getGustomBinding(), string.Empty);

  serviceHost.Open();
}

private static CustomBinding _getGustomBinding()
{
    var binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();
    var httpsTransportBindingElement = new HttpsTransportBindingElement();
    var binding = new CustomBinding(binaryMessageEncodingBindingElement, httpsTransportBindingElement);
    return binding;
}

尽管如此,我有 HttpContext.Current == null (我试图从他的SampleService类方法之一访问它)。

以编程方式托管 WCF 服务时可以访问 HttpContext.Current 吗?有人可以帮我解决这个问题吗?

4

1 回答 1

0

If your website is hosted in IIS7 there has been a change for the Integrated Pipeline that makes the request context unavailable in Application_Start event. When using the Classic mode [NOT RECOMMENDED] (the only mode when running on previous versions of IIS), the request context used to be available, even though the Application_Start event has always been intended as a global and request-agnostic event in the application lifetime. The reason why this can be done (whether it should be done is another discussion) in IIS6 or IIS7 Classic mode is because ASP.NET applications were always started by the first request to the app, therefore it was possible to get to the request context through the static HttpContext.Current.

The above explanation aside I wouldn't recommend hosting your service in this way inside a website. Have a look at this link for hosting within IIS (How to implement a self-hosted service in a console application)

Hope this helps.

于 2010-06-29T14:22:14.197 回答