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クラスのメソッドの1つからアクセスしようとしています)。

WCF サービスがプログラムでホストされている場合、HttpContext.Current にアクセスできますか? 誰でもこの問題で私を助けることができますか?

4

1 に答える 1

0

WebサイトがIIS7でホストされている場合、Application_Startイベントで要求コンテキストを使用できないようにする統合パイプラインの変更があります。クラシックモード[非推奨](以前のバージョンのIISで実行している場合の唯一のモード)を使用する場合、Application_Startイベントは常にアプリケーションでグローバルで要求に依存しないイベントとして意図されていましたが、要求コンテキストは使用可能でした。一生。IIS6またはIIS7クラシックモードでこれを実行できる理由(実行する必要があるかどうかは別の説明です)は、ASP.NETアプリケーションは常にアプリへの最初の要求によって開始されたため、要求コンテキストに到達することができたためです。静的なHttpContext.Currentを介して。

上記の説明はさておき、このようにWebサイト内でサービスをホストすることはお勧めしません。IIS内でのホスティングについては、このリンクを参照してください(コンソールアプリケーションでセルフホストサービスを実装する方法

お役に立てれば。

于 2010-06-29T14:22:14.197 に答える