UFO ET IT

다시 컴파일하지 않고 .NET에서 웹 서비스 주소를 동적으로 전환하려면 어떻게해야합니까?

ufoet 2020. 12. 7. 21:16
반응형

다시 컴파일하지 않고 .NET에서 웹 서비스 주소를 동적으로 전환하려면 어떻게해야합니까?


웹 서비스를 참조하는 코드가 있고 해당 웹 서비스의 주소를 동적으로 (데이터베이스, 구성 파일 등에서 읽음) 쉽게 변경하고 싶습니다. 이것의 주요 용도 중 하나는 컴퓨터 이름과 IP 주소가 다른 여러 환경에 배포하는 것입니다. 웹 서비스 서명은 다른 곳에 위치하는 모든 배포에서 동일합니다.

Visual Studio "웹 참조 추가"마법사에 망설 였을 수도 있습니다. 그래도 비교적 쉬운 작업 인 것 같습니다.


웹 참조를 생성하고 솔루션 탐색기에서 웹 참조를 클릭 할 때. 속성 창에 다음과 같은 내용이 표시됩니다.

웹 참조 속성

값을 dynamic으로 변경하면 app.config에 항목이 추가됩니다.

여기에 더 많은 정보 가있는 CodePlex 기사 가 있습니다.


실제로 동적으로 설정하는 경우 호출중인 프록시 클래스 인스턴스의 .Url 필드를 설정해야합니다.

프로그램 내에서 .config 파일의 값 설정 :

  1. 엉망입니다.

  2. 다음 응용 프로그램이 시작될 때까지 읽지 못할 수 있습니다.

설치 당 한 번만 수행하면되는 작업이라면 다른 포스터에 동의하고 .config 파일과 동적 설정을 사용합니다.


나는 이것이 오래된 질문이라는 것을 알고 있지만 우리의 해결책은 내가 여기에서 보는 것보다 훨씬 간단합니다. VS2010 이상에서 WCF 호출에 사용합니다. 문자열 URL은 앱 설정이나 다른 소스에서 가져올 수 있습니다. 제 경우에는 사용자가 서버를 선택하는 드롭 다운 목록입니다. TheService는 VS add service reference를 통해 구성되었습니다.

private void CallTheService( string url )
{
   TheService.TheServiceClient client = new TheService.TheServiceClient();
   client.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
   var results = client.AMethodFromTheService();
}

나는 며칠 동안이 문제로 어려움을 겪었고 마침내 전구가 클릭되었습니다. 런타임에 웹 서비스의 URL을 변경할 수있는 핵심은 부분 클래스 선언으로 수행 한 생성자를 재정의하는 것입니다. 위의 URL 동작을 동적으로 설정해야합니다.

이것은 기본적으로 웹 서비스 래퍼를 생성하여 서비스 참조 추가를 통해 어떤 시점에서 웹 서비스를 다시로드해야하는 경우 작업을 잃지 않습니다. Partial 클래스에 대한 Microsoft 도움말은 특별히이 구성의 이유 중 일부가 웹 서비스 래퍼를 만드는 것임을 명시합니다. http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.100).aspx

// Web Service Wrapper to override constructor to use custom ConfigSection 
// app.config values for URL/User/Pass
namespace myprogram.webservice
{
    public partial class MyWebService
    {
        public MyWebService(string szURL)
        {
            this.Url = szURL;
            if ((this.IsLocalFileSystemWebService(this.Url) == true))
            {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else
            {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }
    }
}

URL 동작을 " 동적 "으로 변경합니다 .


As long as the web service methods and underlying exposed classes do not change, it's fairly trivial. With Visual Studio 2005 (and newer), adding a web reference creates an app.config (or web.config, for web apps) section that has this URL. All you have to do is edit the app.config file to reflect the desired URL.

In our project, our simple approach was to just have the app.config entries commented per environment type (development, testing, production). So we just uncomment the entry for the desired environment type. No special coding needed there.


Just a note about difference beetween static and dynamic.

  • Static: you must set URL property every time you call web service. This because base URL if web service is in the proxy class constructor.
  • Dynamic: a special configuration key will be created for you in your web.config file. By default proxy class will read URL from this key.

If you are fetching the URL from a database you can manually assign it to the web service proxy class URL property. This should be done before calling the web method.

If you would like to use the config file, you can set the proxy classes URL behavior to dynamic.


Definitely using the Url property is the way to go. Whether to set it in the app.config, the database, or a third location sort of depends on your configuration needs. Sometimes you don't want the app to restart when you change the web service location. You might not have a load balancer scaling the backend. You might be hot-patching a web service bug. Your implementation might have security configuration issues as well. Whether it's production db usernames and passwords or even the ws security auth info. The proper separation of duties can get you into some more involved configuration setups.

If you add a wrapper class around the proxy generated classes, you can set the Url property in some unified fashion every time you create the wrapper class to call a web method.


open solition explorer

웹 서비스를 마우스 오른쪽 버튼으로 클릭하여 URL 동작을 동적으로 변경하십시오.

솔루션 탐색기에서 '모든 파일 표시'아이콘을 클릭하십시오.

웹 참조에서 Reference.cs 파일을 편집하십시오.

생성자 변경

public Service1() {
        this.Url = "URL"; // etc. string  variable this.Url = ConfigClass.myURL
      }

나에게 WebService에 대한 참조는

서비스 참조

.

어쨌든 아주 쉽습니다. 누군가 말했듯이 web.config 파일에서 URL을 변경하면됩니다.

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="YourServiceSoap" />
      </basicHttpBinding>
    </bindings>
    <client>
        **** CHANGE THE LINE BELOW TO CHANGE THE URL **** 
        <endpoint address="http://10.10.10.100:8080/services/YourService.asmx"
          binding="basicHttpBinding" bindingConfiguration="YourServiceSoap"
          contract="YourServiceRef.YourServiceSoap" name="YourServiceSoap" />
    </client>

참고 URL : https://stackoverflow.com/questions/125399/how-can-i-dynamically-switch-web-service-addresses-in-net-without-a-recompile

반응형