【问题标题】:WCF service is not working in browser hosted from a consoleWCF 服务在从控制台托管的浏览器中不起作用
【发布时间】:2020-10-03 05:15:31
【问题描述】:

我在 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();
    }
}

【问题讨论】:

  • "...但无法在另一个项目/解决方案中发现..." - 您的意思是通过 Visual Studio 的添加服务参考吗?
  • 是 @MickyD
  • 您只需要通过代码公开 WCF 服务元数据。 docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/…
  • @MickyD - 它正在工作,我可以在添加服务时浏览和发现方法。我将在下面添加答案。那么,对于学习 WCF,哪个是最好的教程呢?你有什么建议吗?

标签: c# wcf


【解决方案1】:

因此,为了在浏览器中获取服务并在服务参考中发现服务,您必须添加如下所示的 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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2013-03-10
    • 2017-03-17
    相关资源
    最近更新 更多