我有一个使用 System.ServiceModel.ServiceHost 的 .Net Framework 4.7 C# 库,该库在 .Net Core 框架中不可用。
当我从 .Net Framework 4.7 应用程序中调用该库时,ServiceHost 初始化得很好。如果我从 .Net Core 3.1 应用程序中调用同一个库,则会失败并显示
System.TypeLoadException: 'Could not load type 'System.ServiceModel.ServiceHost' from assembly 'System.ServiceModel
加载像 System.ServiceModel.Primitives 这样的 nuget 包并不能解决这个问题。
我必须采取哪些选择才能使这项工作成功?
Microsoft 发布了
CoreWCF
,以便能够在 .NET Framework
中使用 WCF Services
.net Core
。
您至少需要使用
CoreWCF.Primitives
和 CoreWCF.Http
软件包。
您的实际服务的代码应该能够保持不变,因为不应该有任何巨大的变化,只需确保您更新
using
引用,以便它们指向CoreWCF
。
然后,您需要通过添加以下行来更新
Program.cs
文件以包含服务的绑定:
builder.Services.AddServiceModelServices().AddServiceModelMetadata();
var app = builder.Build(); // Make sure the rest of the lines are added after this line
app.UseServiceModel(builder =>
{
builder.AddService((serviceOptions) => { })
// Add a BasicHttpBinding at a specific endpoint
.AddServiceEndpoint<YourService, IYourService>(new BasicHttpBinding(), "/EchoService/basichttp")
// Add a WSHttpBinding with Transport Security for TLS
.AddServiceEndpoint<YourService, IYourService>(new WSHttpBinding(SecurityMode.Transport), "/YourService/WSHttps");
});
var serviceMetadataBehavior = app.Services.GetRequiredService();
serviceMetadataBehavior.HttpGetEnabled = true;
当然,您需要将
IYourService
和 YourService
替换为您自己的版本,其中包括您的 DataContacts
和 ServiceContracts
。