WCF POST方法返回“方法不允许”

时间:2018-02-11 12:47:35

标签: c# rest web-services wcf

我有以下WCF网络服务:

我在IService1中定义

    [OperationContract]
    [WebInvoke(Method = "POST")]
    string testSer();

和In Service1.svc

public string testSer()
{
return "test";
}

我从C#winForm应用程序调用Web服务,如下所示:

var client = new RestClient("http://localhost/webservices/Service1.svc/");


            var request = new RestRequest("testSer", Method.POST);
            IRestResponse response = client.Execute(request);
            var content = response.Content; // raw content as string
            MessageBox.Show(content);

返回的响应是“Method Not Allowed”。如果我将方法类型更改为“GET”,则可以正常工作。

如果我尝试从浏览器调用“POST”方法,则返回的响应是“Method Not Allowed”

我的配置文件:

    <?xml version="1.0"?>
<configuration>
    <connectionStrings>
      <remove name="LocalSqlServer" />
      <add name="LocalSqlServer" connectionString="Data Source=myserver;Initial Catalog=db;User ID=sa;Password=111;" />
    </connectionStrings>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
    <services>

      <service name="WcfService3.Service1">
        <endpoint address="mex" binding="mexHttpBinding"  contract="IMetadataExchange" />  
        <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding"
        bindingConfiguration="jsonp" name="jsonService" contract="WcfService3.IService1" />
        <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="WcfService3.IService1" />

      </service>
    </services> 
  <bindings>
      <basicHttpBinding>
        <binding name="soapService" />
      </basicHttpBinding>
      <webHttpBinding>
        <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>

    <behaviors>
      <endpointBehaviors>
        <behavior name="restfulBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
          <!--<enableWebScript />-->
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"  policyVersion="Policy15" />/>
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

 <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping> 

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
    </modules>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
    <validation validateIntegratedModeConfiguration="false"/>

    <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
      </customHeaders>
</httpProtocol>
  </system.webServer>

</configuration>

修改 当我尝试使用WCF测试客户端(微软Visual Studio附带)测试服务时,我收到以下错误:

错误:无法从https://www.example.net/cms/Service1.svc/TestSer获取元数据如果这是您有权访问的Windows(R)Communication Foundation服务,请检查您是否已在指定地址启用元数据发布。有关启用元数据发布的帮助,请参阅http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange错误URI上的MSDN文档:https://www.example.net/cms/Service1.svc/TestSer元数据包含无法解析的引用:“https://www.example.net/cms/Service1.svc/TestSer”。内容类型application / json;响应消息的charset = utf-8与绑定的内容类型不匹配(application / soap + xml; charset = utf-8)。如果使用自定义编码器,请确保正确实现IsContentTypeSupported方法。响应的前34个字节是:'{“testSerResult”:“test-1 service”}'。HTTP GET错误URI:https://www.example.net/cms/Service1.svc/TestSer下载“https://www.example.net/cms/Service1.svc/TestSer”时出错。请求失败,HTTP状态为405:Method Not Allowed。

3 个答案:

答案 0 :(得分:0)

像下面的代码一样更改webconfig

<system.webServer>
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <remove name="WebDAV" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules>
<remove name="WebDAVModule" />
</modules>
 <security>
    <requestFiltering>
        <verbs allowUnlisted="false">
            <add verb="GET" allowed="true" />
            <add verb="POST" allowed="true" />
            <add verb="DELETE" allowed="true" />
            <add verb="PUT" allowed="true" />
        </verbs>
    </requestFiltering>
  </security>
</system.webServer>

答案 1 :(得分:0)

装饰你的营业合约
[OperationContract]
[WebInvoke(Method = "POST")]

在您的Web Config中应该是这样的:

   <system.serviceModel>
    <client />
    <behaviors>
      <endpointBehaviors>
        <behavior name="restfulBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
          <!--<enableWebScript />-->
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding name="soapService" />
      </basicHttpBinding>
      <webHttpBinding>
        <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="WcfService3.Service1">
        <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="WcfService3.IService1" />
        <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
      </service>
    </services> 
  </system.serviceModel>

这是从后端点返回的数据:

enter image description here

答案 2 :(得分:0)

首先感谢大家,特别感谢@ jalison-evora的帮助。

错误是由于NGinX配置造成的。

请查看此链接

WCF Service Method Not Allowed When Using WebsiteName