本文介绍: 首先我们要创建好webServices项目文件可以是一个项目也可以是一个单独的文件放在其他项目中。创建webServices文件的头部,引用依赖将AJAX调用此web服务取消注释。/// <summary> /// AddApplyOnline 的摘要说明 /// </summary> [WebService(Namespace = “http://192.168.1.48:3030/AddApplyOnline.asmx/AddApplyOnlin
首先我们要创建好webServices项目文件可以是一个项目也可以是一个单独的文件放在其他项目中。
创建webServices文件的头部,引用依赖将AJAX调用此web服务取消注释。
/// <summary>
/// AddApplyOnline 的摘要说明
/// </summary>
[WebService(Namespace = "http://192.168.1.48:3030/AddApplyOnline.asmx/AddApplyOnlineData")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
[SoapHeader("myheader")]
[WebMethod]
public string AddApplyOnlineData(string info)
{
bool result = false;
string resultStr = "";
try
{
//myheader.UserId= HttpContext.Current.Request.Form.Get("UserName");
//myheader.UserPW = HttpContext.Current.Request.Form.Get("PWD");
string msg = "";
if (!myheader.IsValid(out msg))
{
var resultJson = new
{
cod = -1,
resultText = msg,
};
resultStr = JsonConvert.SerializeObject(resultJson);
}
else
{
Dmc_ApplicationRecord info1 = new Dmc_ApplicationRecord();
info1 = JsonConvert.DeserializeObject<Dmc_ApplicationRecord>(info);
#region 表单提交方法
//string txtCustomerName = HttpContext.Current.Request.Form.Get("txtCustomerName");
//string txtCompanyAddress = HttpContext.Current.Request.Form.Get("txtCompanyAddress");
//string txtName = HttpContext.Current.Request.Form.Get("txtName");
//string txtPhone = HttpContext.Current.Request.Form.Get("txtPhone");
//string txtWechat = HttpContext.Current.Request.Form.Get("txtWechat");
//string txtRamark = HttpContext.Current.Request.Form.Get("txtRamark");
//string txtField = HttpContext.Current.Request.Form.Get("txtField");
//info1.CustomerName = txtCustomerName;
//info1.Address = txtCompanyAddress;
//info1.ContactPhone = txtPhone;
//info1.ContactName = txtName;
//info1.WeChat = txtWechat;
//info1.ScopeName = txtField;
//info1.Remark = txtRamark;
#endregion
info1.CreateTime = DateTime.Now;
if (string.IsNullOrEmpty(info1.CustomerName) || string.IsNullOrEmpty(info1.ContactName) || string.IsNullOrEmpty(info1.ContactPhone) || string.IsNullOrEmpty(info1.Remark))
{
var resultJson = new
{
cod = -1,
resultText = "申请失败!必填数据不能为空!",
};
resultStr = JsonConvert.SerializeObject(resultJson);
}
else
{
info1.CreateTime = DateTime.Now;
result = _bLL.AddDmc_ApplicationRecord(info1);
if (result)
{
var resultJson = new
{
cod = 1,
resultText = "申请成功!",
};
resultStr = JsonConvert.SerializeObject(resultJson);
}
else
{
var resultJson = new
{
cod = -1,
resultText = "申请失败!",
};
resultStr = JsonConvert.SerializeObject(resultJson);
}
}
}
}
catch (Exception ex)
{
LogCommonHelper.WriteLogInfo(ex, ex.Message);
var resultJson = new
{
cod = -1,
resultText = "申请失败!",
};
resultStr = JsonConvert.SerializeObject(resultJson);
}
return resultStr;
}
注意:[SoapHeader(“myheader”)]表示soap身份验证myheader为示例的验证类info为参数,resultStr为返回的数据,以json字符串形式返回。参数数据也可以用json字符串来传递过来。
public MySoapHeader myheader = new MySoapHeader();(此为实例化的验证类)验证类代码如下:
using PBDMC.BLL;
using PBDMC.Common;
using PBDMC.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PBDMC.AIO.SoapHeadeHelper
{
public class MySoapHeader : System.Web.Services.Protocols.SoapHeader
{
//账号和密码
private string userID = string.Empty;
private string userPW = string.Empty;
//uuid
private Guid uuID = Guid.Parse("00000000-0000-0000-0000-000000000000");
private Dmc_CustomerInfoBLL _cbll = new Dmc_CustomerInfoBLL();
public string UserId
{
get { return userID; }
set { userID = value; }
}
public string UserPW
{
get { return userPW; }
set { userPW = value; }
}
public Guid UuId
{
get { return uuID; }
set { uuID = value; }
}
public MySoapHeader()
{ }
public MySoapHeader(string name, string password)
{
userID = name;
userPW = password;
}
private bool IsValid(string nUserId, string nPassWord, Guid nuuid, out string nMsg)
{
nMsg = "";
try
{
Guid guid = Guid.Parse("00000000-0000-0000-0000-000000000000");
var info = _cbll.GetDmc_CustomerInfoList().Where(s => s.CustomerUUID != guid && s.CustomerUUID == nuuid).FirstOrDefault();
if (info != null)
{
var Name = info.CustomerName;
var pwd = DESEncrypt.Decrypt(info.CustomerPassword);
if (nUserId == Name && nPassWord == pwd)
{
return true;
}
else
{
nMsg = "账号或者密码错误";
return false;
}
}
else
{
nMsg = "账户不存在";
return false;
}
}
catch
{
nMsg = "账户不存在";
return false;
}
}
private bool IsValid(string nUserId, string nPassWord, out string nMsg)
{
nMsg = "";
try
{
var info = _cbll.GetDmc_CustomerInfoList().Where(s => s.CustomerName == nUserId && s.CustomerPassword == DESEncrypt.Encrypt(nPassWord)).FirstOrDefault();
if (info != null)
{
UuId = info.CustomerUUID;
return true;
}
else
{
nMsg = "账户不存在";
return false;
}
}
catch
{
nMsg = "账户不存在";
return false;
}
}
public bool IsValid(out string nMsg)
{
if (uuID!= Guid.Parse("00000000-0000-0000-0000-000000000000"))
{
return IsValid(userID, userPW, uuID, out nMsg);
}
else
{
return IsValid(userID, userPW, out nMsg);
}
}
}
}
要动态调用首先我们需要准备一个webServices帮助类,代码如下:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Web.Services.Description;
using Microsoft.CSharp;
using System.Xml.Serialization;
namespace PBDMC.Common
{
/// <summary>
/// 动态调用WebService(支持SaopHeader)
/// </summary>
public class WebServiceHelper
{
/// <summary>
/// 获取WebService的类名
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <returns>返回WebService的类名</returns>
private static string GetWsClassName(string wsUrl)
{
string[] parts = wsUrl.Split('/');
string[] pps = parts[parts.Length - 1].Split('.');
return pps[0];
}
/// <summary>
/// 调用WebService(不带SoapHeader)
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <param name="methodName">方法名称</param>
/// <param name="args">参数列表</param>
/// <returns>返回调用结果</returns>
public static object InvokeWebService(string wsUrl, string methodName, object[] args)
{
return InvokeWebService(wsUrl, null, methodName, null, args);
}
/// <summary>
/// 调用WebService(带SoapHeader)
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <param name="methodName">方法名称</param>
/// <param name="soapHeader">SOAP头</param>
/// <param name="args">参数列表</param>
/// <returns>返回调用结果</returns>
public static object InvokeWebService(string wsUrl, string methodName, SoapHeader soapHeader, object[] args)
{
return InvokeWebService(wsUrl, null, methodName, soapHeader, args);
}
/// <summary>
/// 调用WebService
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <param name="className">类名</param>
/// <param name="methodName">方法名称</param>
/// <param name="soapHeader">SOAP头</param>
/// <param name="args">参数列表</param>
/// <returns>返回调用结果</returns>
public static object InvokeWebService(string wsUrl, string className, string methodName, SoapHeader soapHeader, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((className == null) || (className == ""))
{
className = GetWsClassName(wsUrl);
}
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(wsUrl + "?wsdl");
ServiceDescription sd = ServiceDescription.Read(stream);
//配置代理ServiceDescriptionImporter数据
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
//sdi.ProtocolName = "Soap";
//sdi.Style = ServiceDescriptionImportStyle.Server;
//sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
sdi.AddServiceDescription(sd, null, null);
CodeNamespace cn = new CodeNamespace(@namespace);
//生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
//CSharpCodeProvider csc = new CSharpCodeProvider();
///ICodeCompiler icc = csc.CreateCompiler();
CodeDomProvider icc = CodeDomProvider.CreateProvider("CSharp");
//设定编译参数
CompilerParameters cplist = new CompilerParameters();
cplist.GenerateExecutable = false;
cplist.GenerateInMemory = true;
cplist.ReferencedAssemblies.Add("System.dll");
cplist.ReferencedAssemblies.Add("System.XML.dll");
cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
cplist.ReferencedAssemblies.Add("System.Data.dll");
//编译代理类
CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
//生成代理实例,并调用方法
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + className, true, true);
FieldInfo[] arry = t.GetFields();
FieldInfo client = null;
object clientkey = null;
if (soapHeader != null)
{
//Soap头开始
client = t.GetField(soapHeader.ClassName + "Value");
//获取客户端验证对象
Type typeClient = assembly.GetType(@namespace + "." + soapHeader.ClassName);
//为验证对象赋值
clientkey = Activator.CreateInstance(typeClient);
foreach (KeyValuePair<string, object> property in soapHeader.Properties)
{
typeClient.GetField(property.Key).SetValue(clientkey, property.Value);
}
//Soap头结束
}
//实例类型对象
object obj = Activator.CreateInstance(t);
if (soapHeader != null)
{
//设置Soap头
client.SetValue(obj, clientkey);
}
System.Reflection.MethodInfo mi = t.GetMethod(methodName);
return mi.Invoke(obj, args);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
/// <summary>
/// SOAP头
/// </summary>
public class SoapHeader
{
/// <summary>
/// 构造一个SOAP头
/// </summary>
public SoapHeader()
{
this.Properties = new Dictionary<string, object>();
}
/// <summary>
/// 构造一个SOAP头
/// </summary>
/// <param name="className">SOAP头的类名</param>
public SoapHeader(string className)
{
this.ClassName = className;
this.Properties = new Dictionary<string, object>();
}
/// <summary>
/// 构造一个SOAP头
/// </summary>
/// <param name="className">SOAP头的类名</param>
/// <param name="properties">SOAP头的类属性名及属性值</param>
public SoapHeader(string className, Dictionary<string, object> properties)
{
this.ClassName = className;
this.Properties = properties;
}
/// <summary>
/// SOAP头的类名
/// </summary>
public string ClassName { get; set; }
/// <summary>
/// SOAP头的类属性名及属性值
/// </summary>
public Dictionary<string, object> Properties { get; set; }
/// <summary>
/// 为SOAP头增加一个属性及值
/// </summary>
/// <param name="name">SOAP头的类属性名</param>
/// <param name="value">SOAP头的类属性值</param>
public void AddProperty(string name, object value)
{
if (this.Properties == null)
{
this.Properties = new Dictionary<string, object>();
}
Properties.Add(name, value);
}
}
}
}
为方便动态调用我们可以将我们的接口的地址方法名以及类名进行相应的配置动态获取方法如下:
<appSettings>
<!--WebService地址-->
<add key="WebServiceAddress" value="http://192.168.1.110:2222/AddApplyOnline.asmx"/>
<!--WebService提供的类名-->
<add key="ClassName" value="AddApplyOnline"/>
<!--WebService方法名-->
<add key="MethodName" value="CheckLogin"/>
<!--存放dll文件的地址-->
<add key="FilePath" value="E:ProjectFilesPBDMCPBDMC.AIObin"/>(可不加)
</appSettings>
现在我们需要的就是如何动态的调用我们的接口方法了,方法如下:
// 读取配置文件,获取配置信息
string url = ConfigurationManager.AppSettings["WebServiceAddress"];//请求地址
string className = ConfigurationManager.AppSettings["ClassName"];//类名
string methodName = ConfigurationManager.AppSettings["MethodName"];//方法名
string filePath = ConfigurationManager.AppSettings["FilePath"];//文件地址
string DataJa = HttpContext.Current.Request.Form.Get("dataJa");//前端传过来的数据
var dataJa = context.Server.UrlDecode(DataJa);//解码数据
string CustomerName = JsonConvert.DeserializeObject<JObject>(dataJa).Property("UserName").Value.ToString();//获取数据
string CustomerPassword = JsonConvert.DeserializeObject<JObject>(dataJa).Property("PWD").Value.ToString();
string Time = JsonConvert.DeserializeObject<JObject>(dataJa).Property("Time").Value.ToString();
long tempTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
//身份验证
WebServiceHelper.SoapHeader myheader = new WebServiceHelper.SoapHeader("MySoapHeader");//类名
myheader.AddProperty("UserId", CustomerName);
myheader.AddProperty("UserPW", CustomerPassword);
//参数
object[] args = { dataJa };
// 调用WebServiceHelper获取返回值
object r = WebServiceHelper.InvokeWebService(url, className, methodName, myheader, args);
//输出返回值
context.Response.Write(r);
至此我们的就完成啦。此文章是在学习中留作记录,如有侵权请联系删除。
借鉴文章:
https://www.cnblogs.com/dotnet261010/p/12461930.html
动态调用WebService(支持SaopHeader)_北极星的专栏-CSDN博客
原文地址:https://blog.csdn.net/Y2210151431/article/details/122403662
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_27014.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。