[英]WCF service is not working in browser hosted from a console
我在 Windows 控制台中创建了一个简单的 WCF 服务(学习目的)。
该服务能够使用代码(使用相同的 url)使用,但无法在另一个项目/解决方案中发现或无法在浏览器中浏览 url。
我没有使用任何配置文件。 那么我必须做什么才能发现/浏览服务?
我正在使用 c#.net 并引用 System.ServiceModel
我的代码在下面
using System;
using System.ServiceModel;
[ServiceContract]
interface IMyservice
{
[OperationContract]
string GetResult(string value1, string value2);
}
class My Service : IMyService
{
string GetResult(string value1, string value2)
{
return $"First Name : {value1}\nLast Name : {value2}";
}
}
public class Program
{
public static void Main()
{
var host = new ServiceHost(typeOf(MyService));
host.AddServiceEndpoint(typeOf(IMyService), new BasicHttpBinding(), "http://localhost:1234/service1");
host.open();
var service = new ChannelFactory<IMyService>.CreateChannel(new BasicHtpBinding(), new EndpointAddress("http://localhost:1234/service1"));
Console.WriteLine(service.GetResult("Ragesh", "Sivakumar"));
Console.ReadLine();
}
}
因此,为了在浏览器中获取服务并在服务引用中发现服务,您必须添加如下 ServiceMetadataBehavior,
public class Program
{
public static void Main()
{
var host = new ServiceHost(typeOf(MyService));
host.AddServiceEndpoint(typeOf(IMyService), new BasicHttpBinding(), "http://localhost:1234/service1");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
host.open();
var service = new ChannelFactory<IMyService>.CreateChannel(new BasicHtpBinding(), new EndpointAddress("http://localhost:1234/service1"));
Console.WriteLine(service.GetResult("Ragesh", "Sivakumar"));
Console.ReadLine();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.