WCF中,通過C#代碼或App.config配置文件創建ServiceHost類


C#

static void Main(string[] args)
{
    //創建宿主的基地址
    Uri baseAddress = new Uri("http://localhost:8080/User");

    //創建宿主
    using (ServiceHost host = new ServiceHost(typeof(User), baseAddress))
    {
        host.AddServiceEndpoint(typeof(IUser), new WSHttpBinding(), "");

        //將HttpGetEnabled屬性設置為true
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;

        //將行為添加到Behaviors中
        host.Description.Behaviors.Add(smb);

        //打開宿主
        host.Open();
        Console.WriteLine("WCF中的HTTP監聽已啟動....");
        Console.ReadLine();
        host.Close();
    }
}

 

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="WCFLibrary.User">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/User"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="wsHttpBinding" contract="WCFLibrary.IUser"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
public partial class MainForm : Form
{
    ServiceHost host;

    public MainForm()
    {
        InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        host = new ServiceHost(typeof(User));
        //打開宿主
        host.Open();
        this.label1.Text = "WCF中的HTTP監聽已啟動....";
    }

    private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        host.Close();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM