将WCF REST服务作为Windows服务托管

4

我希望创建REST WCF服务并将其安装为Windows服务。 我已经创建了REST WCF服务并运行它,对于xml和json都可以正常工作。 以下是代码文件。 IRestWCFServiceLibrary.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace RestWCFServiceLibrary
{
    // NOTE: If you change the class name "Service1" here, you must also update the             reference to "Service1" in App.config.
    public class RestWCFServiceLibrary : IRestWCFServiceLibrary
    {
        public string XMLData(string id)
        {
            return "Id:" + id;
        }
        public string JSONData(string id)
        {
            return "Id:" + id;
        }
    }
}

RestWCFServiceLibrary.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

namespace RestWCFServiceLibrary
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IRestWCFServiceLibrary
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "xml/{id}")]
        string XMLData(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/{id}")]
        string JSONData(string id);
    }
}

App.config

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must     be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="RestWCFServiceLibrary.Service1Behavior"
        name="RestWCFServiceLibrary.RestWCFServiceLibrary">
        <endpoint address="" binding="webHttpBinding"     contract="RestWCFServiceLibrary.IRestWCFServiceLibrary" behaviorConfiguration="web">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8001/RestWCFServiceLibrary/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="RestWCFServiceLibrary.Service1Behavior">
          <!-- To avoid disclosing metadata information, 
      set the value below to false and remove the metadata endpoint above before     deployment -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="web">
                    <webHttp/>
                </behavior>
            </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

现在我想将其作为Windows服务托管/安装,为此我添加了一个Windows服务项目,并提供了上述创建的RESR WCF的引用。将服务类命名为MyRestWCFRestWinSer。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using RestWCFServiceLibrary;

namespace RestWCFWinService
{
    public partial class MyRestWCFRestWinSer : ServiceBase
    {
        ServiceHost oServiceHost = null;
        public MyRestWCFRestWinSer()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            oServiceHost = new ServiceHost(typeof(MyRestWCFRestWinSer));
            oServiceHost.Open();
        }

       protected override void OnStop()
        {
            if (oServiceHost != null)
            {
                oServiceHost.Close();
                oServiceHost = null;
            }
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace RestWCFWinService
{
    static class Program
    {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new MyRestWCFRestWinSer() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

我添加了项目安装程序,运行了安装程序。运行后,我通过使用installutil命令提示符注册了服务。 服务已成功注册并列在服务列表中。 如果我启动服务,它会出现错误:“RestWCFWinService Service on Local Computer started and the stopped. Some services stop automatically if they are not in use by other services or programs”。
但是,如果我使用SOAP来执行此操作,则完美地工作。
因此,请帮助我将此REST WCF服务安装为Windows服务。

你尝试过使用WebServiceHost而不是ServiceHost吗? - Tim
@Tim 你的意思是将REST WCF作为Web服务进行托管吗? - Hanumantha
不是,它已经是一个网络服务。我是指使用WebServiceHost,它与WCF REST模型相辅相成(它派生自“ServiceHost”)。此外,请检查事件查看器,以查看服务启动时是否记录了任何错误。 - Tim
我建议您遇到了运行时错误,导致服务停止。很可能是配置错误。请检查事件日志。 - Mick
我不认为把服务的类名和命名空间取相同的名字对你有好处。我看不出有什么问题,但我只是不会这样做,因为它可能会引起混淆(就像你似乎正在遇到的问题一样)。尝试更改服务的类名,然后相应地更新配置,例如:<service ... name="RestWCFServiceLibrary.LessConfusingService">。 - Mick
显示剩余4条评论
1个回答

5

我认为有两个问题 - 你已经根据你的评论纠正了其中一个问题。

首先,你使用的是 ServiceHost 而不是 WebServiceHost。我不确定这是否是问题的一部分,但根据你的评论(使用 ServiceHost 时没有在事件查看器中出现错误,改用 WebServiceHost 后出现错误似乎表明它是问题所在)。

第二个问题似乎与你的配置文件有关。你有一个 WCF 服务库(一个 DLL)。按设计,DLL 不使用项目模板中包含的 app.config 文件 - 它们使用消费应用程序的配置文件。在这种情况下,是 Windows 服务。将你的库配置文件中的 <system.serviceModel> 部分复制到 Windows 服务的 app.config 文件中。此时,你的 WCF 类库应该能够接收到终结点。

请注意,Windows 服务配置文件在项目编译后将被命名为 MyRestWCFRestWinSer.exe.config,而不是 App.config


是的,你说得对,我确实漏了 app.config 文件。现在我已经将其添加到了 Windows 服务中。但服务仍然无法启动,而且现在在事件查看器中出现了错误:“无法启动服务。System.Configuration.ConfigurationErrorsException: 没有名为'web'的终结点行为。(C:\Program Files\Default Company Name\MyRestWCFService\RestWCFWinService.exe.Config 第12行)” - Hanumantha
是的,我复制了<system.serviceModel>部分。 据我所知,服务的命名空间和配置文件中的服务名称可能不匹配。我不知道如何设置配置文件以匹配服务命名空间和其他内容。 - Hanumantha
奇怪。配置文件看起来正确,服务名称也没问题。不知道还有什么可以尝试的了。抱歉 :( - Tim
我找到了问题,实际上配置不正确。我使用了不同的应用程序,并提供了正确的配置,现在它正常工作。 谢谢 @Tim - Hanumantha
@Hanumantha,你能发布正确的.config文件吗?我遇到了和你一样的问题。 - Thomas
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接