选项方法不允许。获取Works而不是POST [英] OPTIONS Method not allowed. Get Works but not POST

查看:90
本文介绍了选项方法不允许。获取Works而不是POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using angularJS and this is my code in a factory which makes a http POST call

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没有问题

An http GET call works and I get json back with no issues

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服务代码。另一个团队负责这一点。

By setting the Content-Type to application/json an OPTIONS request is sent out. So far in my tests it appears that setting the content type to "application/x-www-form-urlencoded" is not possible because the web service will only accept json data. I do not have access to modify the web service code. Another team takes care of that.

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

The request headers that goes with OPTIONS is

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方法不允许。

The method is still not allowed. I get "405 method not allowed".

我认为这是因为Access-Control-Allow-Headers正在向我发送类型和Content-Type案例不匹配。

I think it is because the "Access-Control-Allow-Headers" is sending me types and the "Content-Type" case is not matched.

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

The client and the server is running on HTTPS.

任何见解?

角度版本:1.5.7

angular version: 1.5.7

更新

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

The web service developer followed this guide to enable CORS on the server and it worked. http://enable-cors.org/server_wcf.html

推荐答案

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

From the above answer and the URL mentioned 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" />

这篇关于选项方法不允许。获取Works而不是POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆