选项方法不允许。获取作品但不是POST

时间:2016-06-30 16:53:32

标签: javascript angularjs cors cross-domain

我正在使用angularJS,这是我在工厂进行http POST调用的代码

var data = { ticket: JSON.stringify(aticket), "autoAssignDefaultSLA": "true", "autoAssignDefaultPriority": "true" };

            return $http({
                method: 'POST',
                url: requestUrl,
                data: data,
                headers: { 'Content-Type': 'application/json; charset=UTF-8' }
            });

http GET调用有效,我得到了json,没有任何问题

return $http({
                method: 'GET',
                url: requestUrl,
                params: { userToken: userToken, assignedIds: contactId, companyIds: "" }
            });

通过将Content-Type设置为application / json,将发送OPTIONS请求。到目前为止,在我的测试中,似乎无法将内容类型设置为“application / x-www-form-urlencoded”,因为Web服务只接受json数据。我无权修改Web服务代码。另一个团队负责这一点。

与OPTIONS一起使用的请求标头是

Host: staging.url.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
DNT: 1
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: https://url.synbeta.com
Connection: keep-alive

响应标头如下

Access-Control-Allow-Headers: Authorization, Content-Type, If-None-Match, Cookie, Cookies, x-session-id, x-atg-host
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Allow: POST
Cache-Control: private
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Date: Thu, 30 Jun 2016 16:39:48 GMT
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=p5aolcjpwd0qfhqjdbluha1h; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET

仍然不允许使用该方法。我得到“405方法不允许”。

我认为这是因为“Access-Control-Allow-Headers”正在向我发送类型,并且“Content-Type”情况不匹配。

客户端和服务器正在HTTPS上运行。

任何见解?

角度版本:1.5.7

更新

Web服务开发人员遵循本指南在服务器上启用CORS并且工作正常。 http://enable-cors.org/server_wcf.html

1 个答案:

答案 0 :(得分:0)

从上面的答案和提到的URL http://enable-cors.org/server_wcf.html

创建邮件检查器

public class CustomHeaderMessageInspector : IDispatchMessageInspector
            {
                Dictionary<string, string> requiredHeaders;
                public CustomHeaderMessageInspector (Dictionary<string, string> headers)
                {
                    requiredHeaders = headers ?? new Dictionary<string, string>();
                }

                public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
                {
                    return null;
                }

                public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
                {
                    var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
                    foreach (var item in requiredHeaders)
                    {
                        httpHeader.Headers.Add(item.Key, item.Value);
                    }           
                }
            }

创建端点行为并使用Message Inspector添加标题

public class EnableCrossOriginResourceSharingBehavior : BehaviorExtensionElement, IEndpointBehavior
            {
                public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
                {

                }

                public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
                {

                }

                public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
                {
                    var requiredHeaders = new Dictionary<string, string>();

                    requiredHeaders.Add("Access-Control-Allow-Origin", "*");
                    requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
                    requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");

                    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
                }

                public void Validate(ServiceEndpoint endpoint)
                {

                }

                public override Type BehaviorType
                {
                    get { return typeof(EnableCrossOriginResourceSharingBehavior); }
                }

                protected override object CreateBehavior()
                {
                    return new EnableCrossOriginResourceSharingBehavior();
                }
            }

在web.config中注册新行为

 <extensions>
              <behaviorExtensions>        
                <add name="crossOriginResourceSharingBehavior" type="Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral" />        
              </behaviorExtensions>      
            </extensions>

向端点行为配置添加新行为

<endpointBehaviors>      
            <behavior name="jsonBehavior">
                <webHttp />
                <crossOriginResourceSharingBehavior />
            </behavior>
            </endpointBehaviors>

配置端点

<endpoint address="api" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="Service.IServiceContract" />