Quantcast
Channel: てすとぶろぐ
Viewing all articles
Browse latest Browse all 208

Web サービス参照時の認証プロキシ設定(2) config ファイル使わないパターン

$
0
0

前回のメモと同様に、悩ましくてしょうがない認証プロキシ相手で外部サービスを利用する際の方法です。今回は「諸般の事情」で config ファイルを利用しにくいケースに利用できる方法の一つになります。

実際のコードは以下の通りになります。

   1:Dim client As [Service Interface] = Nothing
   2:Try
   3:Dim myBinding = New BasicHttpBinding()
   4:Dim myEndpoint = New EndpointAddress([Service Address])
   5:Dim myChannelFactory = New ChannelFactory(Of [Service Interface])(myBinding, myEndpoint)
   6:  
   7:'認証プロキシの定義
   8:     myBinding.ProxyAddress = New Uri(string.Format("http://{0}:{1}", [Proxy Address], [Proxy Port]))
   9:     myBinding.UseDefaultWebProxy = false
  10:     myBinding.Security.Mode = BasicHttpSecurityMode.Transport
  11:     myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None
  12:     myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic
  13:  
  14:'オレオレ証明書許可対応で呼ぶメソッド設定
  15:'ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf CheckValidationResult)
  16:
  17:'エンドポイントのデフォルト設定を削除
  18:Dim defaultCredentials = myChannelFactory.Endpoint.Behaviors.Find(Of ClientCredentials)()
  19:     myChannelFactory.Endpoint.Behaviors.Remove(defaultCredentials)
  20:  
  21:'認証プロキシの認証情報設定
  22:     ClientCredentials loginCredentials = New ClientCredentials()
  23:     loginCredentials.UserName.UserName = [Account]
  24:     loginCredentials.UserName.Password = [Password]
  25:  
  26:'チャンネルの作成
  27:     myChannelFactory.Endpoint.Behaviors.Add(loginCredentials)
  28:     client = myChannelFactory.CreateChannel()
  29:  
  30:'サービスの実行、結果の取得
  31:Dim apiRet = client.[Service Method](New [Service Class](New [Service Body Class]([Parameter]))).Body.@return
  32:  
  33:'チャンネルの終了
  34:DirectCast(client, ICommunicationObject).Close()
  35:  
  36:Catch ex As Exception
  37:  
  38:If client IsNotNothingThen
  39:DirectCast(client, ICommunicationObject).Abort()
  40:EndIf
  41:  
  42:EndTry
  43:  

config ファイルを用いた初期化処理を、コードで力技にて実行する形ですね。

ポイントとなったのは認証情報の設定方法で、デフォルトで登録される設定を削除しておかないと、うまいこといかないという点です。

そしてここまで試した後で @kazukさんよりすばらしい情報が・・・!

AppDomain を自分で作成することで、好きな場所の config ファイルを扱えるようになるとのことですので、これも試してみようと思います。


Viewing all articles
Browse latest Browse all 208

Trending Articles