简体   繁体   English

WCF 服务在从控制台托管的浏览器中不起作用

[英]WCF service is not working in browser hosted from a console

I have created a simple WCF service in windows console (Learning purpose).我在 Windows 控制台中创建了一个简单的 WCF 服务(学习目的)。

The service is able to consume using code (using same url) but unable to discover in another project/solution or not able to browse the url in browser.该服务能够使用代码(使用相同的 url)使用,但无法在另一个项目/解决方案中发现或无法在浏览器中浏览 url。

I'm not using any config file.没有使用任何配置文件。 So what I have to do to discover/ browse the service?那么我必须做什么才能发现/浏览服务?

I'm using c#.net and referring System.ServiceModel我正在使用 c#.net 并引用 System.ServiceModel

My code is below我的代码在下面

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

So, for getting the service in browser and discovering the service in service reference you have to add ServiceMetadataBehavior like below,因此,为了在浏览器中获取服务并在服务引用中发现服务,您必须添加如下 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM