【超细完整版】C# 获取WebService所有方法并调用 【调用篇】

注意:该文章涉及到的调用方法若找不到 请移步第一部分内容查找


C# 生成wsdl和dll教程请移步
【超细完整版】C# WebService 通过URL生成WSDL文件和DLL文件> 【生成篇】


开始

首先实现一个类,用于实现对URL的验证等

csharp 复制代码
public class InputFormatVerification
{
    /// <summary>
    /// 是否合法Url地址(统一资源定位)
    /// </summary>
    /// <param name="strValue">url地址</param>
    /// <returns>成功返回true 失败返回false</returns>
    public static bool IsUrl(string strValue)
    {
        string RegexStr = string.Empty;
        RegexStr = @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$";
        return formatChecks(RegexStr, strValue);
    }

    /// <summary>
    /// 检测串值是否为合法的格式
    /// </summary>
    /// <param name="strRegex">正则表达式</param>
    /// <param name="strValue">要检测的String值</param>
    /// <returns>成功返回true 失败返回false</returns>
    public static bool formatChecks(string strRegex, string strValue)
    {
        if (string.IsNullOrWhiteSpace(strValue))
        {
            return false;
        }
        Regex re = new Regex(strRegex);
        return re.IsMatch(strValue);
    }
}

实现Invoke

获取WebService中的所有web 方法
csharp 复制代码
#region 获取web方法
/// <summary>
/// 获取WebService接口的所有WebMethod方法
/// 通过WebService方法的特性为【System.Web.Services.Protocols.SoapDocumentMethodAttribute】
/// 根据特性SoapDocumentMethodAttribute来筛选出所有WebMethod方法
/// </summary>
/// <param name="url"></param>
public static List<MethodInfo> GetAllWebMethodsFromLink(string url, out string className)
{
    className = GetClassNameFromUrl(url);
    CompilerResults result = UrlToDllFile(url);
    Assembly assembly = result.CompiledAssembly;
    Type type = assembly.GetType(className);
    return GetWebMethods(type);
}
/// <summary>
/// 获取WebService接口的所有WebMethod方法
/// 通过WebService方法的特性为【System.Web.Services.Protocols.SoapDocumentMethodAttribute】
/// 根据特性SoapDocumentMethodAttribute来筛选出所有WebMethod方法
/// </summary>
/// <param name="wsdlFilePath"></param>
public static List<MethodInfo> GetAllWebMethodsFromWsdl(string wsdlFilePath, out string className)
{
    className = GetClassNameFromWsdl(wsdlFilePath);
    CompilerResults result = WsdlToDll(wsdlFilePath);
    Assembly assembly = result.CompiledAssembly;
    Type type = assembly.GetType(className);
    return GetWebMethods(type);
}

private static List<MethodInfo> GetWebMethods(Type type)
{
    List<MethodInfo> methodInfoList = new List<MethodInfo>();
    if (type == null)
    {
        return methodInfoList;
    }
    MethodInfo[] methodInfos = type.GetMethods();
    for (int i = 0; i < methodInfos.Length; i++)
    {
        MethodInfo methodInfo = methodInfos[i];
        //WebMethod方法的特性为:System.Web.Services.Protocols.SoapDocumentMethodAttribute 
        Attribute attribute = methodInfo.GetCustomAttribute(typeof(System.Web.Services.Protocols.SoapDocumentMethodAttribute));
        if (methodInfo.MemberType == MemberTypes.Method && attribute != null)
        {
            methodInfoList.Add(methodInfo);
        }
    }
    return methodInfoList;
}
#endregion
通过wsdl或url进行调用
csharp 复制代码
/// <summary>
/// 调用WebService
/// </summary>
/// <param name="address">WebService地址</param>
/// <param name="methodName">方法名称</param>
/// <param name="args">参数列表</param>
/// <param name="timeOut"></param>
/// <returns>返回调用结果</returns>
/// <exception cref="Exception"></exception>
private static object InvokeWebService(string address, string methodName, object[] args, string timeOut = "")
{
    try
    {
        string className = string.Empty;
        CompilerResults result = null;
        //支持直接URL或wsdl类型文件的调用
        if (InputFormatVerification.IsUrl(address))
        {
            className = GetClassNameFromUrl(address);
            result = UrlToDllFile(address);
        }
        else
        {
            className = GetClassNameFromWsdl(address);
            result = WsdlToDll(address);
        }

        Assembly assembly = result.CompiledAssembly;
        Type type = assembly.GetType(className);
        FieldInfo[] arry = type.GetFields();
        //实例类型对象   
        object obj = Activator.CreateInstance(type);
        System.Reflection.MethodInfo mi = type.GetMethod(methodName);
        //添加超时时间
        if (!string.IsNullOrEmpty(timeOut))
        {
            int timeout = 0;
            int.TryParse(timeOut, out timeout);

            if (timeout == 0) timeout = 1200;
            //设置超时时间
            ((System.Web.Services.Protocols.WebClientProtocol)(obj)).Timeout = timeout * 1000;//毫秒s,timeOut超时时间设置为分钟
        }
        var res = mi.Invoke(obj, args);
        return res;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
    }
}

老规矩!😄

相关推荐
★YUI★35 分钟前
学习游戏制作记录(玩家掉落系统,删除物品功能和独特物品)8.17
java·学习·游戏·unity·c#
谷宇.1 小时前
【Unity3D实例-功能-拔枪】角色拔枪(二)分割上身和下身
游戏·unity·c#·游戏程序·unity3d·游戏开发·游戏编程
LZQqqqqo2 小时前
C# 中 ArrayList动态数组、List<T>列表与 Dictionary<T Key, T Value>字典的深度对比
windows·c#·list
Dm_dotnet4 小时前
Stylet启动机制详解:从Bootstrap到View显示
c#
三千道应用题6 小时前
WPF&C#超市管理系统(6)订单详情、顾客注册、商品销售排行查询和库存提示、LiveChat报表
开发语言·c#·wpf
唐青枫10 小时前
别滥用 Task.Run:C# 异步并发实操指南
c#·.net
我好喜欢你~17 小时前
C#---StopWatch类
开发语言·c#
一阵没来由的风21 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
一枚小小程序员哈1 天前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
Eternity_GQM1 天前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word