VS2017中的WCF服务错误400错误请求

时间:2018-10-14 16:03:39

标签: wcf

我在VS2017中有一个非常简单的WCF服务项目。但是,当我尝试访问端点时,总是收到错误400。我已经阅读了此处发布的有关同一问题的其他问题,到目前为止,我还没有运气尝试过这些问题。

我的服务合同:

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
            BodyStyle = WebMessageBodyStyle.Wrapped,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetData/{value}")]
    string GetData(string value);
}

我的服务:

public class Service : IService
{
    public string GetData(string value)
    {
        return string.Format("You entered: {0}", value);
    }
}

我的Web.Config:

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="myBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
      <service behaviorConfiguration="myBehavior" name="WCGFService1.Service">
        <endpoint address="" contract="WCGFService1.IService" binding="webHttpBinding">
        </endpoint>
      </service>
    </services>

当我访问http://localhost:61648/Service.svc/GetData/12时,收到HTTP 400错误请求。我已经尝试过使用浏览器和POSTman。我在做什么错了?

我正在使用VS2017。我的IService.cs和Service.cs位于App_Code文件夹中,而 Service.svc在根文件夹中。另外,当我尝试在web.config中添加namecontract时,VS2013建议我使用名称空间和接口/类名称,而VS2017没有建议我使用任何内容,因此我必须手动输入它。

此外,在VS2013中,“接口”和“类”位于根文件夹中,而不是App_Code文件夹中。该项目是VS2017中的WCF应用程序。我的.NET版本是4.5.2。

1 个答案:

答案 0 :(得分:0)

修复后,web.config文件出现了一些问题:

<system.serviceModel>
    <behaviors>
      <!-- Fix 1: Added a endpointBehavoir with webHttp -->
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="myBehavior">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>

    </behaviors>

    <services>
      <!-- Fix 2: Instead of using the full name (WCGFService1.Service), used just the class name (Service) -->
      <service behaviorConfiguration="myBehavior" name="Service">
      <!-- Fix 3: Same thing here, used just the IService instead of full name, also, used the aforementioned endpointBehavoir -->
        <endpoint address="" contract="IService" binding="webHttpBinding" behaviorConfiguration="web">
        </endpoint>
      </service>
    </services>

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

无论出于何种原因,这对我都是如此,在VS2013中,如果您不提供全名(命名空间和类/接口名称),则无法使用,但在VS2017中,仅当您仅提供类时,它才可以使用/接口名称。