【发布时间】:2021-09-14 22:46:28
【问题描述】:
我正在尝试对 WCF 应用程序进行单元测试。 这是我尝试过的:
public class Service1 : IService1
{
public string GetData(int value)
{
string val = ConfigurationManager.AppSettings["mykey"].ToString();
return string.Format("You entered: {0}. mykey={1}", value, val);
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
ServiceHost serviceHost = null;
try
{
string url = "http://localhost:56666/Serivce1";
var baseAddress = new Uri(url);
serviceHost = new ServiceHost(typeof(Service1), baseAddress);
Binding binding = new WSHttpBinding(SecurityMode.None);
serviceHost.AddServiceEndpoint(typeof(IService1), binding, "Service1");
var smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(smb);
serviceHost.Open(); // if this fails, you have to run Visual Studio as admin
BasicHttpBinding myBinding = new BasicHttpBinding();
ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>(myBinding);
EndpointAddress myEndpoint = new EndpointAddress(url);
IService1 wcfClient = myChannelFactory.CreateChannel(myEndpoint);
string s = wcfClient.GetData(39);
serviceHost.Close();
}
finally
{
if (serviceHost != null)
{
((IDisposable)serviceHost).Dispose();
}
}
}
}
}
当我调用 wcfClient.GetData(39); 我收到此错误: System.ServiceModel.EndpointNotFoundException:在 http://localhost:56666/Serivce1 上没有可以接受消息的端点侦听。这通常是由不正确的地址或 SOAP 操作引起的。有关更多详细信息,请参阅 InnerException(如果存在)。 ---> System.Net.WebException:远程服务器返回错误:(404)未找到。
任何想法为什么我会收到此错误以及如何使其工作?
【问题讨论】:
-
谢谢。我可以看到我正在使用的端口已被使用,但即使从另一个程序我也无法与之交谈。请注意,我必须以管理员身份打开 VisualStudio。