本文介绍了jQuery发布到WCF服务返回405错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在刷我的jQuery,在发帖时遇到一个问题,我无法从不断得到405的wcf服务获得响应-不允许使用方法.我的要求对我来说看起来不错,我想知道我是否错过了一些至关重要但显而易见的事情,为什么会这样.

I was recently brushing up on my jQuery and I came accross a problem when going over post, I was unable to get a response from a wcf service I constantly get 405 - Method not allowed. My request looks good to me and I wondered if I've missed something crucial yet obvious as to why this would happen.

这是正在使用的邮政编码:

here is the post code being used:

 $.ajax({
     type: "POST",
     url: "http://localhost:59929/CustomerService/GetCustomers",
     data: null,
     ContentType: "application/json",
     dataType: "json",
     success: function (msg) {
         alert("Called and got: " + msg);
     },
     error: function (result) {
         alert('Service call failed: ' + result.status + '' + result.statusText);
     }
 });

wcf代码如下:

[ServiceContract]
public interface ICustomerService
{   

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    List<Customer> GetCustomers();

    [OperationContract]
    OperationStatus InsertCustomer(Customer cust);
}

,其配置如下:

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

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

提琴手将原始帖子显示为:

Fiddler shows the raw post as:

POST http://localhost:59929/CustomerService/GetCustomers HTTP/1.1
Host: localhost:59929
Connection: keep-alive
Content-Length: 0
Origin: http://localhost:59513
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.60 Safari/537.1
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:59513/LearnJQuery2/ajax/ajax_post.htm
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

并且提琴手也确认了405响应.

and fiddler also confirms the 405 response.

推荐答案

好一阵子我都看了一下,然后才意识到这没什么问题,但有很多麻烦:),所以这里的问题就解决了.

Well I looked at this for quite sometime and then realised there isn't one thing wrong with this but a pleathora :) so heres the issue solved.

所有这些的确必须来自相同的域,并且具有相同的端口和协议,事实并非如此.我将服务移到了应用程序中,并适当地配置了绑定.下一部分是正确装饰WCF服务,因此这里是正确配置服务的代码.

Fist of all they must indeed be from the same domain with the same port and protocol, this was not the case. I moved my service into my application and configured the bindings appropriately. The next part is to adorn your WCF service correctly so here is the code to configure the service correctly.

ICustomerService.cs

ICustomerService.cs

[ServiceContract]
public interface ICustomerService
{
    [OperationContract]
    [WebInvoke(
        Method = "POST" ,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json)]
    List<JSONCustomer> GetCustomers();
}

CustomerService.cs

CustomerService.cs

[AspNetCompatibilityRequirements(RequirementsMode
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class CustomerService : ICustomerService
{
    public List<JSONCustomer> GetCustomers()
    {
        return new List<JSONCustomer> 
        { 
            new JSONCustomer {id = 1, FirstName = "john", LastName = "Doe"},
            new JSONCustomer {id = 2, FirstName = "jane", LastName = "Doe"},        
        };
    }
}

Web.config

Web.config

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="EndpBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" 
               name="CustomerService">
        <endpoint address="" 
                  binding="webHttpBinding"
                  contract="ICustomerService" 
                  behaviorConfiguration="EndpBehavior"/>
      </service>
    </services>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

</configuration>

接下来这是正在使用的ajax代码(整个网页):

Next here is the ajax code being used (entire webpage):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Ajax Post</title>
        <script type="text/javascript" src="../scripts/jquery-1.7.2.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#HelpButton').click(function () {
                    $.post('../CustomerService.svc/GetCustomers', null,
                        function (data) {
                            var custs = data["GetCustomersResult"];
                            var text = '';

                            $(custs).each(function () {
                                text += '<span>' + this.FirstName + ' ' + this.LastName + '</span><br/>';
                            });

                            $('#OutputDiv').html(text);
                        }
                    , 'json');
                });
            });
        </script>
    </head>
    <body>
        <input id="HelpButton" type="button" value="Press me"/>
        <div id="OutputDiv" />
    </body>
</html>

JSONCustomer.cs

JSONCustomer.cs

[DataContract]
public class JSONCustomer
{
    [DataMember]
    public int id { get; set; }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}

我真的希望那些现在遇到问题的人能对此有所帮助,重要的是您要注意一下jquery中的所有内容,绑定,装饰和ajax代码,这将是行不通的.

I truely hope those that are now having issues will find help with this, it is important that you pay attention to all the things, bindings, adornments and ajax code in jquery one little slip and it just won't work.

这篇关于jQuery发布到WCF服务返回405错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 12:47