向现有项目添加新的WCF服务

本文关键字:WCF 服务 添加 项目 | 更新日期: 2023-09-27 18:18:25

我正在为一个项目添加一个新的WCF服务,但是新的服务与旧的服务不一样。

每个都有一个相似的SVC文件:

<%@ ServiceHost Language="C#" Debug="true" Service="Company.Project.Service1"  %>

每个接口都有一个定义ServiceContract和OperationContracts的接口:

[ServiceContract]
[ServiceKnownType(typeof(Service1))]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "json/method1", RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
    ResponseObject Method1(RequestObject req);
}

每个都在web中定义。配置文件:

  <service name="Company.Project.Service1" behaviorConfiguration="ServiceBehavior">
    <endpoint address="rest" binding="webHttpBinding" contract="Company.Project.IService1" behaviorConfiguration="web"/>
    <endpoint address="soap" binding="basicHttpBinding" contract="Company.Project.IService1"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>

然而,当我在使用Chrome的预生产环境中访问原始服务的URL时,我看到了我期望的"方法不允许"错误(因为我使用GET)。

当我访问新服务时,我得到一个404错误:
Server Error in [Snipped]
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 
Requested URL: /[Snipped]/Service2.svc/rest/json/method2

另一个奇怪的是,它在我以前的预生产环境中工作,所以它可能只是部署过程中的东西。

向现有项目添加新的WCF服务

确保在全局中定义了路由。已添加到现有项目中的新服务的ax文件。这很容易被忽略,并导致无法通过托管环境中的Asp.net管道定位资源。

所以,如果你有新版本的服务,比如ApiService2,你需要添加这样的条目:

routes.Add(new ServiceRoute("api2", new ServiceHostFactory(), typeof(ApiService2)));

我注意到你的方法名为Method1,但你试图访问method2

你的web配置是否也有像下面这样的endpointBehavior部分?你需要它来为你的webHttpBinding启用REST端点。你可能还应该添加一个服务行为

<behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="web">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>