jQuery .ajax()405(不允许的方法)/跨域

Lui*_*uis 6 javascript ajax wcf jquery json

我已经看到了很多关于此的问题,但是我找不到代码中缺少的东西.

我正在实施CORS因为我不想使用JSONP.

我知道这是一个preflighted请求,我想我正在添加正确的headers.

错误是网站似乎不喜欢我WCF和每次我做一个请求,OPTION即使我有Access-Control-Allow-Methods标题,也会调用一个方法.

我只想做一个POST打到我WCFcontentType: "application/json",

WCF是自托管的,Web应用程序已启用IIS 7.5.


Chrome显示的内容:

在此输入图像描述


小提琴手的节目 在此输入图像描述


合同

<OperationContract()>
<WebInvoke(Method:="POST",
           RequestFormat:=WebMessageFormat.Json,
           ResponseFormat:=WebMessageFormat.Json,
           BodyStyle:=WebMessageBodyStyle.WrappedRequest)>
<FaultContract(GetType(ServiceFault))>
Function LookUpPerson(person As Person) _
                     As List(Of Person)
Run Code Online (Sandbox Code Playgroud)

的app.config

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<bindings>
  <webHttpBinding>
    <binding name="webHttpBindingWithJsonP"
             crossDomainScriptAccessEnabled="true">
      <security mode="None" />
    </binding>
  </webHttpBinding>
</bindings>

<services>
  <service name="Project.Services.Person">  
    <endpoint address="ws"  binding="wsHttpBinding"     contract="Project.Services.Interfaces.IPublic" />   
    <endpoint address=""    binding="webHttpBinding"    contract="Project.Services.Interfaces.IPublic"
              behaviorConfiguration="jsonBehavior"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8732/" />
      </baseAddresses>
    </host>
  </service>
</services>

<extensions>
  <behaviorExtensions>
    <add name="customHeaders"
         type="Project.Services.Utilities.EnableCrossOriginResourceSharingBehavior, Project.Services, Version=1.0.0.0, Culture=neutral"/>
  </behaviorExtensions>
</extensions>

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <webHttp/>
    <customHeaders />
  </behavior>
</endpointBehaviors>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$.ajax({
    url: "http://192.168.0.61:8282/Project.Services.Person/LookUpPerson",
    type: "POST",
    contentType: "application/json",
    crossDomain: true,
    dataType: "json",
    data: { person: JSON.stringify(person) },
    success: function (data) {
        // doing something
    },
    error: function (error) {
        // doing something
    }
});
Run Code Online (Sandbox Code Playgroud)

根据http://enable-cors.org/server_wcf.html,在WCF上我有以下处理程序

Public Class CustomHeaderMessageInspector
        Implements IDispatchMessageInspector

        Private requiredHeaders As Dictionary(Of String, String)
        Public Sub New(headers As Dictionary(Of String, String))
            requiredHeaders = If(headers, New Dictionary(Of String, String)())
        End Sub

        Public Function AfterReceiveRequest(ByRef request As System.ServiceModel.Channels.Message,
                                            channel As System.ServiceModel.IClientChannel,
                                            instanceContext As System.ServiceModel.InstanceContext) _
                                        As Object _
                                        Implements System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest
            Return Nothing
        End Function

        Public Sub BeforeSendReply(ByRef reply As System.ServiceModel.Channels.Message,
                                   correlationState As Object) _
                               Implements System.ServiceModel.Dispatcher.IDispatchMessageInspector.BeforeSendReply
            Dim httpHeader = TryCast(reply.Properties("httpResponse"), HttpResponseMessageProperty)
            For Each item In requiredHeaders
                httpHeader.Headers.Add(item.Key, item.Value)
            Next
        End Sub

    End Class
Run Code Online (Sandbox Code Playgroud)

Public Class EnableCrossOriginResourceSharingBehavior
        Inherits BehaviorExtensionElement
        Implements IEndpointBehavior

        Public Sub AddBindingParameters(endpoint As ServiceEndpoint, bindingParameters As System.ServiceModel.Channels.BindingParameterCollection) _
                                        Implements System.ServiceModel.Description.IEndpointBehavior.AddBindingParameters

        End Sub

        Public Sub ApplyClientBehavior(endpoint As ServiceEndpoint, clientRuntime As System.ServiceModel.Dispatcher.ClientRuntime) _
                                         Implements System.ServiceModel.Description.IEndpointBehavior.ApplyClientBehavior

        End Sub

        Public Sub ApplyDispatchBehavior(endpoint As ServiceEndpoint, endpointDispatcher As System.ServiceModel.Dispatcher.EndpointDispatcher) _
                                        Implements System.ServiceModel.Description.IEndpointBehavior.ApplyDispatchBehavior
            Dim requiredHeaders = New Dictionary(Of String, String)()

            requiredHeaders.Add("Access-Control-Allow-Origin", "*")
            requiredHeaders.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
            requiredHeaders.Add("Access-Control-Allow-Headers", "Origin, Content-Type, Accept")
            requiredHeaders.Add("Access-Control-Max-Age", "1728000")

            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(New CustomHeaderMessageInspector(requiredHeaders))
        End Sub

        Public Sub Validate(endpoint As ServiceEndpoint) _
            Implements System.ServiceModel.Description.IEndpointBehavior.Validate

        End Sub

        Public Overrides ReadOnly Property BehaviorType() As Type
            Get
                Return GetType(EnableCrossOriginResourceSharingBehavior)
            End Get
        End Property

        Protected Overrides Function CreateBehavior() As Object
            Return New EnableCrossOriginResourceSharingBehavior()
        End Function

    End Class
Run Code Online (Sandbox Code Playgroud)

对不起,很长的帖子,我想具体一点.

提前致谢.


UPDATE

如果我使用contentType: "text/plain"我在chrome控制台上得到错误:

POST http://192.168.0.61:8282/Project.Services.Person/LookUpPerson400(错误请求)

Pie*_*ick 10

我有同样的问题,这为我解决了.

更改

[WebInvoke(Method = "Post")]
Run Code Online (Sandbox Code Playgroud)

[WebInvoke(Method = "*")]
Run Code Online (Sandbox Code Playgroud)

因为虽然你接受POST,但现代浏览器总会发送OPTIONS.