C# windows 服务 - 暴露 Web 界面

Posted

技术标签:

【中文标题】C# windows 服务 - 暴露 Web 界面【英文标题】:C# windows service - expose web interface 【发布时间】:2019-07-22 18:20:53 【问题描述】:

我创建了一个公开 Web 界面的 Web 服务。 该服务以控制台模式运行,我看到了 Web 界面

    public ServiceHost serviceHost = null; public ServiceHost serviceHost = null;;

    private readonly TestService s;
    public Service()
    


        InitializeComponent();
        s = new TestService();
    

    protected override void OnStart(string[] args)
    
        Logger.Info("Start event");
        if (serviceHost != null)
        
            serviceHost.Close();
        

        // Create a ServiceHost for the CalculatorService type and 
        // provide the base address.
        string baseAddress = "http://localhost:8000/Service";
        serviceHost = new ServiceHost(typeof(Service1), new System.Uri(baseAddress));
        serviceHost.AddServiceEndpoint(typeof(WindowsServiceTemplate.IService1),
                    new BasicHttpBinding(), baseAddress);

        // Check to see if the service host already has a ServiceMetadataBehavior

        ServiceMetadataBehavior smb = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
        // If not, add one
        if (smb == null)
            smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
        serviceHost.Description.Behaviors.Add(smb);
        // Add MEX endpoint
        serviceHost.AddServiceEndpoint(
          ServiceMetadataBehavior.MexContractName,
          MetadataExchangeBindings.CreateMexHttpBinding(),
          "mex"
        );



        // Open the ServiceHostBase to create listeners and start 
        // listening for messages.
        serviceHost.Open();
        s.Start();
    

    protected override void OnStop()
    

        Logger.Info("Stop event");
        if (serviceHost != null)
        
            serviceHost.Close();
            serviceHost = null;
        
        s.Stop();
    

    protected override void OnShutdown()
    
        Logger.Info("Windows is going shutdown");
        Stop();
    


    public void Start()
    
        OnStart(null);
    



和 app.config 文件:

<system.serviceModel>
<services>
  <!-- Note: the service name must match the configuration name for the service implementation. -->
  <service name="WindowsServiceTemplate.IService1" behaviorConfiguration="MyServiceTypeBehaviors" >
    <!-- Add the following endpoint.  -->
    <!-- Note: your service must have an http base address to add this endpoint. -->
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mexHttpBinding" />
  </service>
</services>

<behaviors>
  <serviceBehaviors>
    <behavior name="MyServiceTypeBehaviors" >
      <!-- Add the following element to your service behavior configuration. -->
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
</behaviors>

app.config 中的配置文件(控制台应用程序项目) 我可以访问 http://localhost:8000/Service 但是当我尝试调用测试方法时 http://localhost:8000/Service/test 我收到 404 错误。

我错过了什么?

【问题讨论】:

【参考方案1】:

使用 Webhttpbinding 创建服务和 webservicehost 来托管服务。我做了一个demo,希望对你有用。

public partial class Service1 : ServiceBase
    
        ServiceHost sh = new ServiceHost(typeof(MyService), new Uri("http://localhost:5900"));
        public Service1()
        
            InitializeComponent();
        

        protected override void OnStart(string[] args)
        
            if (sh.State==CommunicationState.Opened)
            
                Log("Service open Fail");
            
            else
            
                WebHttpBinding webHttpBinding = new WebHttpBinding();
                ServiceEndpoint se = sh.AddServiceEndpoint(typeof(IService), webHttpBinding, "");
                se.EndpointBehaviors.Add(new WebHttpBehavior());
                sh.Open();
                Log("Service is ready....");
            
        

        protected override void OnStop()
        
            if (sh.State==CommunicationState.Opened)
            
                sh.Close();
                Log("Service closed successfully");
            
        
        private void Log(string text)
        
            using (StreamWriter sw=new StreamWriter(@"D:\log.txt",true))
            
                sw.WriteLine($"text----Time:DateTime.Now.ToShortTimeString()");
            
        
        [ServiceContract]
        public interface IService
        
            [OperationContract]
            [WebGet]
            string SayHello();
        
        public class MyService : IService
        
            public string SayHello()
            
                return "Hello Stranger";
            
        

安装。 结果。 这是官方文档。https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-create-a-basic-wcf-web-http-service 如果有什么可以帮助的,请随时告诉我。

【讨论】:

感谢问题是使用 HttpBasicBinding 而不是 webHttpBinding 如果可能,请将其标记为有用,以便其他人愿意看到回复。

以上是关于C# windows 服务 - 暴露 Web 界面的主要内容,如果未能解决你的问题,请参考以下文章

从 C# Windows 窗体调用 PHP Web 服务

Windows 服务和 Web 服务之间的进程间通信

基于C#实现Windows服务

如何在 Windows 服务中托管一个简单的 ASP.NET Web 界面

如何在 .Net 中为 Windows 服务创建 Web 界面? [关闭]

在 Mono 中将 C++ 暴露给 C#:函数的无效转换?