1. 创建webservice服务
- 新建asp.net项目,选择.net framework 4.7.2
- 新建webservice服务
- 修改代码
using System.Web.Services;
using System.Web.Services.Protocols;
namespace WebService01
{
/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://www.wujialiang.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
/// <summary>
/// 简单测试
/// </summary>
/// <returns></returns>
[WebMethod(Description ="HelloWord接口")]
public string HelloWorld()
{
return "Hello World";
}
/// <summary>
/// 复杂类型
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
[WebMethod(Description ="加法计算")]
public ResultModel Add(int a, int b)
{
var c = a + b;
return new ResultModel()
{
Success = true,
Result = c
};
}
//声明Soap头实例
public MySoapHeader diyHeader = new MySoapHeader();
/// <summary>
/// 授权验证
/// </summary>
/// <returns></returns>
[System.Web.Services.Protocols.SoapHeader("diyHeader")]
[WebMethod(Description ="授权验证的数据")]
public string GetAuthData()
{
if (diyHeader.UserName == "wjl" && diyHeader.PassWord == "wujialiang")
return "通过授权";
else
return "未通过授权";
}
}
public class ResultModel
{
public bool Success { get; set; }
public int Result { get; set; }
}
/// <summary>
/// 自定义SoapHeader
/// </summary>
public class MySoapHeader : SoapHeader
{
private string userName = string.Empty;
private string passWord = string.Empty;
/// <summary>
/// 构造函数
/// </summary>
public MySoapHeader()
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
public MySoapHeader(string userName, string passWord)
{
this.userName = userName;
this.passWord = passWord;
}
/// <summary>
/// 获取或设置用户用户名
/// </summary>
public string UserName
{
get { return userName; }
set { userName = value; }
}
/// <summary>
/// 获取或设置用户密码
/// </summary>
public string PassWord
{
get { return passWord; }
set { passWord = value; }
}
}
}
- 启动webservice查看效果
2. httpclient调用
- 创建控制台应用程序
- 编写代码
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace WebServiceUse01
{
public class Program
{
static string url = "http://localhost:59523/WebService1.asmx";
static void Main(string[] args)
{
HelloWordTest().Wait();
Console.WriteLine("HelloWordTest执行完毕....");
AddTest().Wait();
Console.WriteLine("AddTest执行完毕....");
GetAuthDataTest().Wait();
Console.WriteLine("GetAuthDataTest执行完毕....");
GetAuthDataFailTest().Wait();
Console.WriteLine("GetAuthDataFailTest执行完毕...");
Console.ReadKey();
}
/// <summary>
/// 测试helloWord接口
/// </summary>
static async Task HelloWordTest()
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/HelloWorld");
StringBuilder body = new StringBuilder();
body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
body.Append("<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/\">");
body.Append("<soap:Body>");
body.Append("<HelloWorld xmlns=\"http://www.wujialiang.com/\" />");
body.Append("</soap:Body>");
body.Append("</soap:Envelope>");
StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
var response = await httpClient.PostAsync(url, content);
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("获取数据失败");
return;
}
var resultXml = await response.Content.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(resultXml);
var result = doc.GetElementsByTagName("soap:Envelope");
Console.WriteLine(result.Count);
if (result.Count > 0)
{
Console.WriteLine(result[0].InnerText);
}
}
/// <summary>
/// 测试加法
/// </summary>
/// <returns></returns>
static async Task AddTest()
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/Add");
StringBuilder body = new StringBuilder();
body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
body.Append("<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/\">");
body.Append("<soap:Body>");
body.Append("<Add xmlns=\"http://www.wujialiang.com/\">");
body.Append("<a>1</a>");
body.Append("<b>2</b>");
body.Append("</Add>");
body.Append("</soap:Body>");
body.Append("</soap:Envelope>");
StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
var response = await httpClient.PostAsync(url, content);
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("获取数据失败");
return;
}
var resultXml = await response.Content.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(resultXml);
var result = doc.GetElementsByTagName("soap:Envelope");
Console.WriteLine(result.Count);
if (result.Count > 0)
{
Console.WriteLine(result[0].InnerText);
Console.WriteLine(result[0].InnerXml);
}
}
/// <summary>
/// 认证数据测试
/// </summary>
/// <returns></returns>
static async Task GetAuthDataTest()
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/GetAuthData");
StringBuilder body = new StringBuilder();
body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
body.Append("<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/\">");
body.Append("<soap:Header>");
body.Append("<MySoapHeader xmlns=\"http://www.wujialiang.com/\">");
body.Append("<UserName>wjl</UserName>");
body.Append("<PassWord>wujialiang</PassWord>");
body.Append("</MySoapHeader>");
body.Append("</soap:Header>");
body.Append("<soap:Body>");
body.Append("<GetAuthData xmlns=\"http://www.wujialiang.com/\" />");
body.Append("</soap:Body>");
body.Append("</soap:Envelope>");
StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
var response = await httpClient.PostAsync(url, content);
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("获取数据失败");
return;
}
var resultXml = await response.Content.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(resultXml);
var result = doc.GetElementsByTagName("soap:Envelope");
Console.WriteLine(result.Count);
if (result.Count > 0)
{
Console.WriteLine(result[0].InnerText);
Console.WriteLine(result[0].InnerXml);
}
}
/// <summary>
/// 认证数据测试
/// </summary>
/// <returns></returns>
static async Task GetAuthDataFailTest()
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/GetAuthData");
StringBuilder body = new StringBuilder();
body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
body.Append("<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/\">");
body.Append("<soap:Header>");
body.Append("<MySoapHeader xmlns=\"http://www.wujialiang.com/\">");
body.Append("<UserName>wjl</UserName>");
body.Append("<PassWord>wujidddaliang</PassWord>");
body.Append("</MySoapHeader>");
body.Append("</soap:Header>");
body.Append("<soap:Body>");
body.Append("<GetAuthData xmlns=\"http://www.wujialiang.com/\" />");
body.Append("</soap:Body>");
body.Append("</soap:Envelope>");
StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
var response = await httpClient.PostAsync(url, content);
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("获取数据失败");
return;
}
var resultXml = await response.Content.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(resultXml);
var result = doc.GetElementsByTagName("soap:Envelope");
Console.WriteLine(result.Count);
if (result.Count > 0)
{
Console.WriteLine(result[0].InnerText);
Console.WriteLine(result[0].InnerXml);
}
}
}
}
- 测试
备注也可以通过webRequest实现
原理一样,代码稍微不同
var url = $"{options.Value.SSOUrl}/TokenService.asmx";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
//发送请求
webRequest.Method = "POST";
//编码
webRequest.ContentType = "text/xml";
webRequest.Headers["SOAPAction"] = "http://passport.alaibao.cn/IfExistsGetUid";
//字符转字节
byte[] bytes = Encoding.UTF8.GetBytes(body.ToString());
Stream writer = webRequest.GetRequestStream();
writer.Write(bytes, 0, bytes.Length);
writer.Flush();
writer.Close();
string result = "";
//返回 HttpWebResponse
try
{
HttpWebResponse hwRes = webRequest.GetResponse() as HttpWebResponse;
if (hwRes.StatusCode == System.Net.HttpStatusCode.OK)
{//是否返回成功
Stream rStream = hwRes.GetResponseStream();
//流读取
StreamReader sr = new StreamReader(rStream, Encoding.UTF8);
result = sr.ReadToEnd();
sr.Close();
rStream.Close();
}
else
{
result = "连接错误";
}
//关闭
hwRes.Close();
}
catch (Exception ex)
{
}