我目前正准备消费SOAP web service然而,在 .NET 项目 (C#) 中,用于服务类型和操作的命名约定非常糟糕与 C# .NET 项目典型的命名约定不一致。
我的问题本质上是:有没有办法在我的客户端实现中自动为生成的 SOAP Web 服务代理类型/方法指定别名?
我希望有某种方法可以使用别名映射来执行 WSDL 转换,以便生成(或重新生成)的类型使用诸如 Contact
之类的名称,但映射到底层contactObject
定义。
由于我不知道在生成期间可以执行任何转换,因此我目前正在手动(或至少在 T4 的帮助下)为类编写包装器,但这似乎是不必要的级别间接;更不用说,这是一件令人头疼的事情。
我正在阅读 Svcutil 上的文档,但尚未找到任何适用的标志。
最佳答案
我已将其发布到您的 other question但你是对的,它更适合这个:
我假设您通过添加“添加服务引用...”来使用此第三方服务,该服务会为 Reference.cs 中的每个类自动生成一些代码,其签名可能如下所示:
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.thirdpartyguys.net")]
public partial class qux: object, System.ComponentModel.INotifyPropertyChanged {
你希望它不是 qux,而是 Qux。如果到目前为止这与您的模型相似,那么您只需将 qux 更改为 Qux,但将 TypeName="qux"
添加到 XmlTypeAttribute
中,并将所有引用更改为引用文献中的此类。这会在 SOAP 中维护正确的 xml 架构,但您可以在项目中更改名称:
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.thirdpartyguys.net", TypeName = "qux")]
public partial class Qux: object, System.ComponentModel.INotifyPropertyChanged {
当然,如果该 XmlType 属性尚未在用于定义命名空间的类中,您可以添加它。它只是没有命名空间参数。我刚刚对此进行了测试,它确实允许我使用该服务,并且只需在我使用它的任何地方通过不同的名称调用一个对象即可。
这对你有用吗?
编辑:(向 future 的读者介绍 SchemaImporterExtension 的想法) 据我了解,当从 WSDL 添加服务引用时,此扩展类可能会调用与默认代码生成行为的偏差。您最终仍然会有一些 Reference.cs 作为您的项目和服务之间的链接,但您可以更改生成的内容。因此,例如,如果我们希望对象始终以大写字母开头,我认为想法是做这样的事情(未经测试):
public class test : SchemaImporterExtension
{
public override string ImportSchemaType(string name, string ns, XmlSchemaObject context,
XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit,
CodeNamespace codeNamespace, CodeGenerationOptions options, CodeDomProvider codeGenerator)
{
if (name[0].CompareTo('a') >= 0) //tests if first letter is lowercase
{
CodeExpression typeNameValue = new CodePrimitiveExpression(name);
CodeAttributeArgument typeNameParameter = new CodeAttributeArgument("TypeName", typeNameValue);
CodeAttributeDeclaration xmlTypeAttribute = new CodeAttributeDeclaration("XmlTypeAttribute", typeNameParameter);
compileUnit.AssemblyCustomAttributes.Add(xmlTypeAttribute);
return name.Substring(0, 1).ToUpper() + name.Substring(1);
}
return null;
}
}
理论上,这将写入 XmlType 属性并将名称更改为正确的大小写,从而在 SOAP 中维护正确的 XML 映射。理论上,使用 SchemaImporterExtension 的优点是对服务引用的更新不会覆盖更改。此外,可以进行一般性的更改,而不是针对每个特定的引用。
欢迎成功使用 SchemaImporterExtension 的人提出评论或编辑。
关于.net - 自动别名生成的 SOAP 代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22097706/