2012-02-28 3 views
6

클래스 라이브러리의 서비스 참조에 3 개의 웹 서비스가 추가되었습니다 (API 용도의 샘플 프로젝트 임) 프로젝트으로 이동해야하지만 보안 문제로 인해 서비스 참조를 추가 할 수 없습니다. 보안 문제는 서비스가 하나의 IP 주소에만 응답하고 고객 서버의 IP 주소라는 것을 의미합니다.) 해당 particaluar 웹 서비스에 "Ildasm.exe"를 사용하는 것과 같은 클래스를 생성 할 수있는 방법이 있습니까?참조를 추가하지 않고 웹 서비스를 사용 하시겠습니까?

+0

서비스가 특정 IP 주소에만 응답하는 경우 코드 테스트 방법을 어떻게 계획합니까? 내 제안은 그것의 소유자로부터 서비스의 WSDL을 잡는 것이고 당신은 svcutil을 실행하여 그것과 상호 작용할 클래스를 생성 할 수 있어야한다. – Rich

답변

8

당신은 웹 서비스 코드를 연주 웹 서비스 참조를 추가 할 필요가 없습니다 :

wsdl.exe의 /out:d:/Proxy.cs/순서 : 수동 예 놀 클래스를 생성 할 수 있습니다 http://localhost:2178/Services.asmx

그리고이 파일을 수동으로 프로젝트에 추가 할 수 있습니다.

+1

나를 이길 :) 참조 목적으로 -> http://msdn.microsoft.com/en-us/library/ms155134.aspx – SeanCocteau

+0

나는 svcutil.exe를 조사 할 것을 제안한다 –

32

이 클래스를 사용할 수 있습니다. 나는 기본 코드를 찾은 곳을 기억하지 못했고, 몇 가지 메소드를 추가하고 이전에 클래스로 변환했다.

public class WebService 
{ 
    public string Url { get; set; } 
    public string MethodName { get; set; } 
    public Dictionary<string, string> Params = new Dictionary<string, string>(); 
    public XDocument ResultXML; 
    public string ResultString; 

    public WebService() 
    { 

    } 

    public WebService(string url, string methodName) 
    { 
     Url = url; 
     MethodName = methodName; 
    } 

    /// <summary> 
    /// Invokes service 
    /// </summary> 
    public void Invoke() 
    { 
     Invoke(true); 
    } 

    /// <summary> 
    /// Invokes service 
    /// </summary> 
    /// <param name="encode">Added parameters will encode? (default: true)</param> 
    public void Invoke(bool encode) 
    { 
     string soapStr = 
      @"<?xml version=""1.0"" encoding=""utf-8""?> 
      <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
       xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
       xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> 
       <soap:Body> 
       <{0} xmlns=""http://tempuri.org/""> 
        {1} 
       </{0}> 
       </soap:Body> 
      </soap:Envelope>"; 

     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url); 
     req.Headers.Add("SOAPAction", "\"http://tempuri.org/" + MethodName + "\""); 
     req.ContentType = "text/xml;charset=\"utf-8\""; 
     req.Accept = "text/xml"; 
     req.Method = "POST"; 

     using (Stream stm = req.GetRequestStream()) 
     { 
      string postValues = ""; 
      foreach (var param in Params) 
      { 
       if (encode) 
        postValues += string.Format("<{0}>{1}</{0}>", HttpUtility.UrlEncode(param.Key), HttpUtility.UrlEncode(param.Value)); 
       else 
        postValues += string.Format("<{0}>{1}</{0}>", param.Key, param.Value); 
      } 

      soapStr = string.Format(soapStr, MethodName, postValues); 
      using (StreamWriter stmw = new StreamWriter(stm)) 
      { 
       stmw.Write(soapStr); 
      } 
     } 

     using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream())) 
     { 
      string result = responseReader.ReadToEnd(); 
      ResultXML = XDocument.Parse(result); 
      ResultString = result; 
     } 
    } 
} 

그리고 당신이

WebService ws = new WebService("service_url", "method_name"); 
ws.Params.Add("param1", "value_1"); 
ws.Params.Add("param2", "value_2"); 
ws.Invoke(); 
// you can get result ws.ResultXML or ws.ResultString 
+0

이것을 사용하기 위해 웹 API를 호출하는 방법이 가능합니까? 메소드 호출? – altandogan

+0

http://stackoverflow.com/questions/40394297/consume-web-service-dynamically-using-httpwebrequest-with-service-reference에서 의견을 말하십시오. –

0

처럼 사용할 수있는 예는 다른

2

당신은 동적으로 서비스 참조의 URL을 변경할 수있을 것입니다 참조 wsdl.exe /out:d:/Proxy.cs /order을 추가하려는 해달라고 :

var service = new MyService.MyWSSoapClient(); 
service.Endpoint.Address = new System.ServiceModel.EndpointAddress("http://localhost:8080/"); 
2

다음은 C# 코드에서 "GET"웹 서비스를 호출하는 방법의 예입니다 :

public string CallWebService(string URL) 
{ 
    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(URL); 
    objRequest.Method = "GET"; 
    objRequest.KeepAlive = false; 

    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); 
    string result = ""; 
    using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) 
    { 
     result = sr.ReadToEnd(); 
     sr.Close(); 
    } 
    return result; 
} 

단순히 URL을 전달하면 응답이 포함 된 문자열이 반환됩니다. 여기에서, 당신은 유용한 무언가로 문자열을 켭니다 JSON.Net "DeserializeObject"함수를 호출 할 수 있습니다 :이 도움이

string JSONresponse = CallWebService("http://www.inorthwind.com/Service1.svc/getAllCustomers"); 

List<Customer> customers = JsonConvert.DeserializeObject<List<Customer>>(JSONresponse); 

희망을.

관련 문제