Web服务,而不添加引用
本文关键字:添加 引用 服务 Web | 更新日期: 2023-09-27 18:26:05
我在类库的服务引用中添加了3个web服务。(这是API使用的示例项目)我需要将这些移动到我的项目中,但由于安全问题,我无法添加服务引用(安全问题是指服务只响应一个ip地址,这是我们客户服务器的ip地址。)有没有方法为特定的web服务生成类似使用"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
您不需要添加web服务引用来播放web服务代码:您可以手动生成要播放的类,例如:
wsdl.exe/out:d:/Proxy.cs/orderhttp://localhost:2178/Services.asmx
然后您可以手动将此文件添加到您的项目中。
以下是如何从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<Customer> customers = JsonConvert.DeserializeObject<List<Customer>>(JSONresponse);
希望这能有所帮助。
您可以动态更改服务引用的url:
var service = new MyService.MyWSSoapClient();
service.Endpoint.Address = new System.ServiceModel.EndpointAddress("http://localhost:8080/");
是的,如果您不想添加参考wsdl.exe /out:d:/Proxy.cs /order
将是替代
如果您使用带有json的wcf服务,您可以实现我在其中一个项目中使用的示例post方法。您需要newtonsoftjson包;
public static ResponseCL PostPurchOrder(PurchaseOrder order)
{
ResponseCL res = new ResponseCL();
string methodUrl = $"{_main.ws_url}/AddPurchaseOrder";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(methodUrl);
httpWebRequest.ContentType = "application/json;";
//if use basic auth//
//string username = "user";
//string password = "1234";
//string encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
//httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(order));
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
res = JsonConvert.DeserializeObject<ResponseCL>(result);
}
return res;
}
使用Microsoft.AspNet.WebApi.Client包的另一种方法如下;
public static ResponseCL PostPurchOrder2(PurchaseOrder order)
{
ResponseCL res = new ResponseCL();
using (var client = new HttpClient())
{
string methodUrl = $"{_main.ws_url}/AddPurchaseOrder";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync(methodUrl, order);
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
string responseString = response.Result.Content.ReadAsStringAsync().Result;
res = JsonConvert.DeserializeObject<ResponseCL>(responseString);
}
}
return res;
}