Web服务没有添加引用?

我有3个Web服务添加到类库中的服务引用。(这是一个API使用的示例项目)我需要将它们移动到我的项目中但由于安全问题我无法添加服务引用(安全问题我意味着服务只响应一个IP地址,这是我们客户服务器的IP地址。)是否有办法为该particaluar Web服务生成类似于使用“Ildasm.exe”的类?

您不需要添加Web服务引用来使用Web服务代码:您可以手动生成要使用的类,例如:

wsdl.exe /out:d:/Proxy.cs / order http:// localhost:2178 / Services.asmx

然后,您可以手动将此文件添加到项目中。

你可以使用这个类。 我不记得我在哪里找到了基本代码,我之前添加了一些方法并转换为类。

public class WebService { public string Url { get; set; } public string MethodName { get; set; } public Dictionary Params = new Dictionary(); public XDocument ResultXML; public string ResultString; public WebService() { } public WebService(string url, string methodName) { Url = url; MethodName = methodName; } ///  /// Invokes service ///  public void Invoke() { Invoke(true); } ///  /// Invokes service ///  /// Added parameters will encode? (default: true) public void Invoke(bool encode) { string soapStr = @"   <{0} xmlns=""http://tempuri.org/""> {1}   "; 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}", HttpUtility.UrlEncode(param.Key), HttpUtility.UrlEncode(param.Value)); else postValues += string.Format("<{0}>{1}", 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 

您可以动态更改服务引用的URL:

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

以下是如何从C#代码调用“GET”Web服务的示例:

 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 customers = JsonConvert.DeserializeObject>(JSONresponse); 

希望这可以帮助。

是的,如果你不想添加引用wsdl.exe /out:d:/Proxy.cs /order将是另一种选择