gpt4 book ai didi

c# - 不添加引用的 Web 服务?

转载 作者:太空狗 更新时间:2023-10-29 20:42:44 25 4
gpt4 key购买 nike

我有 3 个 Web 服务添加到类库中的服务引用。(这是 API 使用的示例项目)我需要将它们移动到我的项目,但我无法添加服务引用因为安全问题(我所说的安全问题是指该服务仅响应一个 IP 地址,即我们客户服务器的 IP 地址。)有没有一种方法可以生成一个类,例如为该特定网站使用“Ildasm.exe”服务?

最佳答案

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

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

关于c# - 不添加引用的 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9482773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com