dotnet-svcutil.xmlserializer NuGet 包可以为 .NET Core 项目预生成序列化程序集。 它为 WCF 服务协定使用的客户端应用程序中的类型预生成 C# 序列化代码,并且可以由 XmlSerializer 序列化。 这提高了序列化或反序列化这些类型的对象时 XML 序列化的启动性能。
先决条件
- .NET Core 2.1 SDK 或更高版本
- 你喜欢的代码编辑器
可以使用命令 dotnet --info 检查已安装的 .NET SDK 和运行时的版本。
入门指南
若要在 .NET Core 控制台应用程序中使用 dotnet-svcutil.xmlserializer ,请执行以下作:
使用 .NET Framework 中的默认模板“WCF 服务应用程序”创建名为“MyWCFService”的 WCF 服务。 在服务方法上添加
[XmlSerializerFormat]属性,如下所示:[ServiceContract] public interface IService1 { [XmlSerializerFormat] [OperationContract(Action = "http://tempuri.org/IService1/GetData", ReplyAction = "http://tempuri.org/IService1/GetDataResponse")] string GetData(int value); }将 .NET Core 控制台应用程序创建为面向 .NET Core 2.1 或更高版本的 WCF 客户端应用程序。 例如,使用以下命令创建名为“MyWCFClient”的应用:
dotnet new console --name MyWCFClient若要确保项目面向 .NET Core 2.1 或更高版本,请检查项目文件中的
TargetFrameworkXML 元素:<TargetFramework>netcoreapp2.1</TargetFramework>通过运行以下命令将包引用添加到
System.ServiceModel.Http:dotnet add package System.ServiceModel.Http添加 WCF 客户端代码:
using System.ServiceModel; class Program { static void Main(string[] args) { var myBinding = new BasicHttpBinding(); var myEndpoint = new EndpointAddress("http://localhost:2561/Service1.svc"); //Fill your service url here var myChannelFactory = new ChannelFactory<IService1>(myBinding, myEndpoint); IService1 client = myChannelFactory.CreateChannel(); string s = client.GetData(1); ((ICommunicationObject)client).Close(); } } [ServiceContract] public interface IService1 { [XmlSerializerFormat] [OperationContract(Action = "http://tempuri.org/IService1/GetData", ReplyAction = "http://tempuri.org/IService1/GetDataResponse")] string GetData(int value); }运行以下命令以添加对
dotnet-svcutil.xmlserializer包的引用:dotnet add package dotnet-svcutil.xmlserializer运行此命令应将条目添加到项目文件,如下所示:
<ItemGroup> <DotNetCliToolReference Include="dotnet-svcutil.xmlserializer" Version="1.0.0" /> </ItemGroup>通过运行
dotnet build来生成应用程序。 如果一切成功,则会在输出文件夹中生成名为 MyWCFClient.XmlSerializers.dll 的程序集。 如果工具未能生成程序集,则生成输出中会显示警告。例如,通过在浏览器中运行
http://localhost:2561/Service1.svc来启动 WCF 服务。 然后启动客户端应用程序,它将在运行时自动加载和使用预生成的序列化程序。