public bool AutoCode_WebServices(string wsUrl, string[] imPorts, string ClassName, string outputFilePath)
{
HttpParamsHelp httpParams = new HttpParamsHelp();
//ws地址
httpParams.Uri = wsUrl;
httpParams.Method = "GET";
httpParams.KeepAlive = true;
httpParams.Accept_Charset = "UTF-8";
//方法数量
int MethodCount;
if (httpParams.GetHttpResponse())
{
//ws页面数据
var text = httpParams.ResponseStr.ToString().Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("\t", "");
//正则匹配方法节点集
Regex reg = new Regex("<xs:schema.*?</xs:schema");
Match ma = reg.Match(text);
string FunContent = ma.Value.ToString();
if (FunContent.Equals(""))
{
//未匹配到数据
return false;
}
//创建代码模板
CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace sampleNamespace = new CodeNamespace("song_AutoCode");
foreach (string import in imPorts)
{
sampleNamespace.Imports.Add(new CodeNamespaceImport(import));
}
CodeTypeDeclaration _class = new CodeTypeDeclaration(ClassName);
//定义生成接口
_class.IsInterface = true;
//正则匹配方法名及其参数
reg = new Regex("<xs:complexType name=\"(.*?)\">(.*?)complexType");
MatchCollection mags = reg.Matches(FunContent);
MethodCount = 0;
foreach (Match mc in mags)
{
CodeMemberMethod method = new CodeMemberMethod();
//设置方法返回值 此处默认返回都是String
method.ReturnType = new CodeTypeReference("System.String");
//接口方法名称
method.Name = mc.Groups[1].Value;
if (method.Name.Contains("Response"))
{
//返回部分暂跳过
continue;
}
MethodCount++;
string inPut = mc.Groups[2].Value;
//正则筛选入参及类型
reg = new Regex(".*?name=\"(.*?)\".*?type=\"xs:(.*?\")");
mags = reg.Matches(inPut);
foreach (Match item in mags)
{
//参数名
string name = item.Groups[1].Value;
//入参类型
string type = item.Groups[2].Value.Replace("\"", "");
switch (type)
{
case "string":
case "decimal":
{
type = "System." + type;
break;
}
case "int":
type = "System.Int32";
break;
case "dateTime":
type = "DateTime";
break;
}
method.Parameters.Add(new CodeParameterDeclarationExpression(type, name));
}
_class.Members.Add(method);
}
sampleNamespace.Types.Add(_class);
unit.Namespaces.Add(sampleNamespace);
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
options.BlankLinesBetweenMembers = true;
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFilePath + ClassName + ".cs"))
{
provider.GenerateCodeFromCompileUnit(unit, sw, options);
}
return true;
}
return false;
}
C#对接webservice 接口自动生成
最新推荐文章于 2023-09-13 10:14:53 发布