c\#세 가지 방법 으로 WebService 인 터 페 이 스 를 호출 합 니 다.

1.인용*.wdl 파일
웹 서비스 서버 에 서 는 wdl 파일 을 제공 합 니 다.클 라 이언 트 는 이 파일 을 통 해.cs 파일 을 생 성하 고.dll 을 생 성 합 니 다.
메모:서버 에서 제공 하 는 URL 만 있 으 면 URL 뒤에'?wdl"브 라 우 저 에 접근 하여 페이지 내용 을 복사 하고 텍스트 파일 에 붙 여 넣 으 며 파일 접 두 사 를"wdl"로 바 꾸 면 wdl 파일 을 얻 을 수 있 습 니 다.
URL 이나 wsdl 파일 을 통 해.cs 파일 을 생 성 할 수 있 습 니 다.
.cs 파일 을 만 드 는 방법 은 두 가지 가 있 습 니 다.다음 과 같 습 니 다.
방법 1:VS 명령 행 도구 로 생 성

위의 그림 에서 보 듯 이"wdl/language:c\#/n:CHEER.Presentation Layer/out:생 성 클래스 의 물리 적 경로(cs 파일 을 먼저 만들어 야 함)WebService 인터페이스 URL 이나 wdl 파일 물리 적 경로"를 입력 하면 됩 니 다.
방법 2:VS 에 외부 도구 추가(나중에 사용 하기 편 함)
VS 도구 메뉴->외부 도구->다음 그림

위의 빨간색 상자 에 있 는 매개 변 수 를 입력 하 십시오.명령 은 C:\Program Files(x86)\Microsoft SDK\\Windows\v 10.0 A\bin\NETFX 4.6.1 Tools\wdl.exe,즉 wdl.exe 의 물리 적 경 로 를 입력 하 십시오.
초기 디 렉 터 리:$(ItemDir)는 현재 프로젝트 루트 디 렉 터 리 아래 를 표시 합 니 다.
네 임 스페이스 를 사용 할 때 사용자 정의 이름 으로 바 꾸 면 됩 니 다.
다음 그림 은 이 외부 도구 의 사용 입 니 다.네 임 스페이스 이름 을 사용자 정의 한 다음 out:뒤에 빈 칸 을 추가 하고 WebService 의 URL 이나 wdl 파일 의 물리 적 경 로 를 추가 합 니 다.


2.이미 알 고 있 는 WebService 인터페이스의 URL,직접 호출
VS 에 서비스 인용-고급-웹 인용 추가 웹 서비스 URL 직접 입력

그 다음 에 이 네 임 스페이스 에 있 는 클래스 의 대상 을 직접 예화 하고 이 인터페이스 에 있 는 여러 방법 을 호출 하면 됩 니 다.
3.동적 호출 WebService
도움말 클래스 만 들 기

/// <summary>
  ///     WebService    
  /// </summary>
  public class WebServiceHelper
  {
    #region InvokeWebService
    /// < summary>
    ///     web  
    ///< /summary> 
    /// < param name="url">WSDL    < /param>
    /// < param name="methodname">   < /param>
    /// < param name="args">  < /param>
    /// < returns>< /returns>
    public object InvokeWebService(string url, string methodname, object[] args)
    {
      return this.InvokeWebService(url, null, methodname, args);
    }

    /// < summary>
    ///     web  
    /// < /summary>
    /// < param name="url">WSDL    < /param>
    /// < param name="classname">  < /param>
    /// < param name="methodname">   < /param> 
    /// < param name="args">  < /param> 
    /// < returns>< /returns> 
    public object InvokeWebService(string url, string classname, string methodname, object[] args)
    {
      string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
      if ((classname == null) || (classname == ""))
      {
        classname = WebServiceHelper.GetWsClassName(url);
      }
      try
      {
        //  WSDL 
        WebClient wc = new WebClient();
        if (!url.ToUpper().Contains("WSDL"))
        {
          url = string.Format("{0}?{1}", url, "WSDL");
        }
        Stream stream = wc.OpenRead(url);
        ServiceDescription sd = ServiceDescription.Read(stream);
        ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
        sdi.AddServiceDescription(sd, "", "");
        CodeNamespace cn = new CodeNamespace(@namespace);
        //          
        CodeCompileUnit ccu = new CodeCompileUnit();
        ccu.Namespaces.Add(cn);
        sdi.Import(cn, ccu);
        CSharpCodeProvider icc = new CSharpCodeProvider();
        //      
        CompilerParameters cplist = new CompilerParameters();
        cplist.GenerateExecutable = false;
        cplist.GenerateInMemory = true;
        cplist.ReferencedAssemblies.Add("System.dll");
        cplist.ReferencedAssemblies.Add("System.XML.dll");
        cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
        cplist.ReferencedAssemblies.Add("System.Data.dll");
        //      
        CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
        if (true == cr.Errors.HasErrors)
        {
          StringBuilder sb = new StringBuilder();
          foreach (CompilerError ce in cr.Errors)
          {
            sb.Append(ce.ToString());
            sb.Append(Environment.NewLine);
          }
          throw new Exception(sb.ToString());
        }
        //      ,      
        System.Reflection.Assembly assembly = cr.CompiledAssembly;
        Type t = assembly.GetType(@namespace + "." + classname, true, true);
        object obj = Activator.CreateInstance(t);
        System.Reflection.MethodInfo mi = t.GetMethod(methodname);
        return mi.Invoke(obj, args);
      }
      catch (Exception ex)
      {
        throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
      }
    }
     
    private static string GetWsClassName(string wsUrl)
    {
      string[] parts = wsUrl.Split('/');
      string[] pps = parts[parts.Length - 1].Split('.');
      if (pps[0].Contains("?"))
      {
        return pps[0].Split('?')[0];
      }
      return pps[0];
    }
    #endregion
  }
WebServiceHelper

WebServiceHelper
그리고 다음 과 같이 호출 합 니 다.

WebServiceHelper webService = new WebServiceHelper();
      object obj= webService.InvokeWebService("http://127.0.0.1:8001/WebService1.asmx", "Add", new object[] {22,33 });
      DataTable dt = obj as DataTable;
메모:이 방법 은 가격 보다 번 거 롭 습 니 다.InvokeWebService 를 호출 할 때마다 메모리 에 동적 프로그램 집합 을 만 들 고 효율 이 매우 낮 습 니 다.
이상 은 c\#세 가지 방법 으로 웹 서비스 인 터 페 이 스 를 호출 하 는 상세 한 내용 입 니 다.c\#웹 서비스 인 터 페 이 스 를 호출 하 는 데 관 한 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기