【问题标题】:WCF and Ajax. Method not allowed is driving me crazyWCF 和 Ajax。不允许的方法让我发疯
【发布时间】:2012-11-20 10:00:41
【问题描述】:

我正在将 ajax 连接到 wcf 服务。但是继续获取​​方法是不允许的。调试了几天。我不明白。 我只是在测试默认的 GetData(int value) 方法。

阿贾克斯:

    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
   $.ajax({
            type: "POST",
            url: "http://localhost:19478/Service1.svc/GetData",
            data: JSON.stringify({"value": "test"}),
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
             success: function (msg) {
                        alert(msg);
                    },
         error: function (msg) {
                        alert("Failed");
                    }
        });

        function OnSuccessCall(response) {
            alert(response);
        }


        function OnErrorCall(response) {
            alert(response.status + " " + response.statusText);
        }

        </script>

web.config:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>





    <services>
      <service name="WcfServiceTest.Service1" behaviorConfiguration="myServiceBehavior">
        <endpoint name="webHttpBinding"
                  address="" binding="webHttpBinding"
                  contract="WcfServiceTest.IService1"
                  behaviorConfiguration="webHttp"
                  >
        </endpoint>
        <endpoint name="mexHttpBinding"
                  address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange"
                  />
      </service>
    </services>






    <behaviors>

      <serviceBehaviors>
        <behavior name="myServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior>

          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>


      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>

        <behavior name="NewBehavior0">
          <webHttp helpEnabled="true"/>

        </behavior>
      </endpointBehaviors>

    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        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"/>
  </system.webServer>

</configuration>

Iservice1:

 [OperationContract]
        [WebInvoke(Method="POST",
        RequestFormat=WebMessageFormat.Json,
        ResponseFormat=WebMessageFormat.Json)]
        string GetData(String value);

服务1:

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

public class Service1 : IService1 上面什么都没有。 在public interface IService1上方有一个[ServiceContract]

我添加了很多东西,删除了很多东西..我不知道了。 我怀疑它是我的 web.config 文件,我不明白那部分

【问题讨论】:

  • 尝试指定UriTemplate,它应该类似于WebInvoke(Method="POST", UriTemplate="GetData")。另外,jsonpjson 不一样,所以你应该在你的ajax 调用中使用dataType: "json"
  • 尝试了第一件事。 Json 的问题在于它给了我不允许的错误方法和Origin null is not allowed by Access-Control-Allow-Origin。我刚刚做的是将我的 ajax 文件移动到我的 wcf 项目的根目录。我收到此错误:'There was an error deserializing the object of type System.String. End element 'root' from namespace '' expected. Found element 'value' from namespace
  • 最后一个错误的原因是参数的类型不匹配。我不确定如何解决,但您可以尝试删除或更改合同中的 RequestFormat=WebMessageFormat.Json。

标签: c# jquery ajax wcf web-config


【解决方案1】:

您的操作合同表明它是一个 post 方法,但您以 JSONP 的形式请求它,它仅支持 Get 请求。如果它不是跨域请求,则不需要使用 JSONP,只需将方法设置为 Post 为您的请求并删除类型,您的响应格式也不是 JSON 对象,也可以根据您的需要通过更改合同或更改方法中的返回数据,然后它应该可以工作。

编辑评论:

首先 JSONP 不是实际的 xmlhttprequest 对象请求。它所做的是向您的页面添加一个脚本标签,该标签具有以请求数据作为参数的回调函数。它主要针对跨域数据共享。 JSONP 请求返回如下内容

请求网址:domain.com/getJsonp?callback=processJSONP

哪个返回;

processJSONP( {
   resultList: [{data: "hello"}, 
                {data: "world"}
   // and lost of data you need.
   ]
});

请注意 processJSONP 这已成为您在页面或库中的功能,并随心所欲。

function processJSONP(jsonpResult) {
   for(var key in jsonpResult.resultList)
   {
      //process the data
   }
}

如果您确实需要使用 POST 获取数据,那么它不能是 JSONP。它必须是 AJAX 请求,并且必须在同一个域中。这样就可以在AJAX请求的成功函数中处理数据了。

【讨论】:

  • 这确实很有意义。 Json 的问题是它给了我两个错误方法不允许和Origin null is not allowed by Access-Control-Allow-Origin 而且,它必须是一个 POST 方法。 GET 不支持输入参数
  • 根据 JSONP 的定义,它只是 GET 吗?如果我需要 POSTWHATEVER 怎么办?有时会从客户那里得到非常奇怪的规格......
  • 知道了。所以,基本上,对于 CORS,我们只能使用 GET,对吗?由于 JSONP 是跨域调用的“唯一”方法,它只能使用 GET...感觉有点令人惊讶,但我相信你的话。
【解决方案2】:

好的,2天后,我修好了。

这是我的步骤,感谢所有做出贡献的人。

  1. 在我的 IService 界面中,我将它添加到了我的 webinvoke:

    BodyStyle = WebMessageBodyStyle.WrappedRequest

  2. 将数据类型从 jsonp 更改为 json,jsonp 仅支持 GET(感谢 Onur TOPAL)。

  3. 将我的 ajax/json 文件放在我的 Visual Studio 项目文件夹中。这将使它在 IIS 服务器上运行。

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 2011-10-01
    • 2021-07-06
    • 2019-10-27
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多