简体   繁体   中英

WCF service is not working in browser hosted from a console

I have created a simple WCF service in windows console (Learning purpose).

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.

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

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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