使用SoapCore时WSDL中缺失DerivedClass,该如何解决?
解决SoapCore中WSDL不显示DerivedClass定义的问题
要让DerivedClass出现在WSDL中,你需要在服务契约接口上也添加[XmlInclude(typeof(DerivedClass))],仅在基类上添加该特性不足以让SoapCore的WSDL生成器识别到派生类型。
具体修改方案
有两种添加方式:
- 在单个操作契约上添加
[ServiceContract(Namespace = "http://example.org/")] public interface ITesting { [OperationContract] [XmlInclude(typeof(DerivedClass))] // 新增此特性 public BaseClass Test(BaseClass someObj); }
- 在整个服务契约接口上添加(适用于多个操作都涉及该派生类的场景)
[ServiceContract(Namespace = "http://example.org/")] [XmlInclude(typeof(DerivedClass))] // 新增此特性 public interface ITesting { [OperationContract] public BaseClass Test(BaseClass someObj); }
原因说明
SoapCore使用XmlSerializer生成WSDL时,元数据是基于服务契约(ITesting接口)的定义来生成的。虽然基类上的[XmlInclude]能让序列化器在运行时处理派生类,但WSDL生成器需要在契约层面明确感知到这些类型,才能将它们包含到WSDL的类型定义中。
修改后的完整代码示例
using SoapCore; using System.ServiceModel; using System.Xml.Serialization; internal class Program { private static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers().AddXmlSerializerFormatters(); builder.Services.AddSoapCore(); builder.Services.AddScoped<ITesting, Testing>(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.UseSoapEndpoint<ITesting>("/Testing", new SoapEncoderOptions(), SoapSerializer.XmlSerializer); }); app.MapControllers(); app.Run(); } } public class Testing : ITesting { private IWebHostEnvironment Environment; public Testing(IWebHostEnvironment _environment) { Environment = _environment; } public BaseClass Test(BaseClass someObj) { throw new NotImplementedException(); } } [ServiceContract(Namespace = "http://example.org/")] [XmlInclude(typeof(DerivedClass))] // 服务契约级别添加XmlInclude public interface ITesting { [OperationContract] public BaseClass Test(BaseClass someObj); } [Serializable] public class DerivedClass : BaseClass { [XmlElement] public string DerivedProp { get; set; } } [Serializable] [XmlInclude(typeof(DerivedClass))] public class BaseClass { [XmlElement] public string BaseProp { get; set; } }
内容的提问来源于stack exchange,提问作者Dialecticus
相关产品推荐
相关产品推荐

