简体   繁体   English

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

[英]WCF POST Method returning “Method not allowed”

I have the following WCF web service: 我有以下WCF Web服务:

I defined in IService1 我在IService1中定义

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

and In Service1.svc 和在Service1.svc中

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

I am calling the web service, from C# winForm application like this: 我正在从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);

The response returned is "Method Not Allowed". 返回的响应为“方法不允许”。 If I change the method type to "GET" it works. 如果我将方法类型更改为“ GET”,那么它将起作用。

If I tried to call the "POST" method from the browser the response returned is "Method Not Allowed" 如果我尝试从浏览器中调用“ POST”方法,则返回的响应为“ Method Not Allowed”

My config file: 我的配置文件:

    <?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>

EDIT When I tried to test the service using WCF Test Client (That comes with Microsoft visual studio) I recieve the following error : 编辑当我尝试使用WCF测试客户端(Microsoft Visual Studio附带)测试服务时,出现以下错误:

Error: Cannot obtain Metadata from https://www.example.net/cms/Service1.svc/TestSer If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. 错误:无法从https://www.example.net/cms/Service1.svc/TestSer获取元数据。如果这是您可以访问的Windows(R)Communication Foundation服务,请检查是否已在指定的地址。 For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: https://www.example.net/cms/Service1.svc/TestSer Metadata contains a reference that cannot be resolved: ' https://www.example.net/cms/Service1.svc/TestSer '. 有关启用元数据发布的帮助,请参阅MSDN文档, 网址http://go.microsoft.com/fwlink/?LinkId=65455。WS-MetadataExchange错误URI: https : //www.example.net/cms/Service1 .svc / TestSer元数据包含无法解析的引用:' https : //www.example.net/cms/Service1.svc/TestSer '。 The content type application/json; 内容类型为application / json; charset=utf-8 of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8). 响应消息的charset = utf-8与绑定的内容类型不匹配(application / soap + xml; charset = utf-8)。 If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. 如果使用自定义编码器,请确保正确实施IsContentTypeSupported方法。 The first 34 bytes of the response were: '{"testSerResult":"test-1 service"}'.HTTP GET Error URI: https://www.example.net/cms/Service1.svc/TestSer There was an error downloading ' https://www.example.net/cms/Service1.svc/TestSer '. 响应的前34个字节为:'{“ testSerResult”:“ test-1服务”}'。HTTP GET错误URI: https ://www.example.net/cms/Service1.svc/TestSer下载“ https://www.example.net/cms/Service1.svc/TestSer ”。 The request failed with HTTP status 405: Method Not Allowed. 请求失败,HTTP状态为405:不允许使用方法。

change webconfig like the code below 像下面的代码一样更改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>

Decorate your Operation contract with 装饰您的运营合同

[OperationContract]
[WebInvoke(Method = "POST")]

And in your Web Config should be like this: 并且在您的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>

This is your data returned from the post endpoint: 这是从post端点返回的数据:

在此处输入图片说明

First thanks you all and especially for @jalison-evora for his help. 首先,谢谢大家,尤其感谢@ jalison-evora的帮助。

The error was due to NGinX configuration. 该错误是由于NGinX配置引起的。

Please check this link 请检查此链接

WCF Service Method Not Allowed When Using WebsiteName 使用WebsiteName时不允许使用WCF服务方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM