Angular CORS飞行前请求导致400错误请求,但邮递员请求有效 [英] Angular CORS preflight request causes 400 Bad Request, but Postman request works OK

查看:51
本文介绍了Angular CORS飞行前请求导致400错误请求,但邮递员请求有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular应用程序在我的开发机器上本地运行,试图向运行在另一台机器上IIS上的WCF Web服务发出请求.

I have an Angular app running locally on my dev machine that's trying to make a request to a WCF web service running on IIS on another machine.

使用邮递员,我可以使用POST和OPTIONS动词向服务提出请求.

Using Postman I can make requests to the service OK, both with POST and OPTIONS verbs.

但是,当我的Angular应用发出请求时,我从发出的CORS预检OPTIONS请求中得到了400错误.

However, when my Angular app makes a request, I end up with a 400 error from the CORS preflight OPTIONS request that's made.

这样发出请求:

  // passed-in url is https://myserver/myservice/Hello
  public hello( url: string, name: string )
  {
     const headers = new HttpHeaders()
     headers.append('Content-Type', 'application/json');
     headers.append('Test', 'TestyTest');

     return this.httpClient.post<string>( url,
        { name: name },
        { headers: headers }
     );
  }

在网络"面板上的Chrome调试工具中,我看到了一个请求的两个条目:

In Chrome's debugging tools on the Network panel I see two entries for this one request:

Hello   (failed)    xhr         zone.js:2935    0 B 188 ms
Hello   400         text/html   Other           0 B 176 ms

如果我检查了这两个条目的请求标头,则看不到我的代码尝试添加的 Test 标头.这不是问题(我不需要该标头),但这可能是一个线索.

If I examine the request headers for both of those entries, in neither do I see the Test header that my code tried to add. This isn't a problem (I don't need that header), but it may be a clue.

标题"第一个条目的面板显示:

The "Headers" panel for the first entry shows:

第二个条目显示:

请注意,第二个内容上的 Content-Type 标头是 text/html .

Note that the Content-Type header on this 2nd one is text/html.

在控制台中,我看到以下内容:

In the console I see this:

我在Web服务的日志中看不到任何条目,或者在IIS日志或服务器上的事件查看器中看不到任何错误.

I'm not seeing any entries in my web service's log, or any errors in the IIS logs or in Event Viewer on the server.

是什么原因导致此问题,如何解决或获取更多信息?

What can be causing this problem, and how can I fix it, or get more info?

推荐答案

这是由CORS引起的.不要使用全局文件来解决跨域问题.您可以尝试使用IDispatchMessageInspector解决跨域问题.

This is caused by CORS. Do not use Global files to solve cross-domain problems. You can try to use IDispatchMessageInspector to solve cross-domain problems.

将SOAP.cs添加到您的项目:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;

    namespace Demo_rest_ConsoleApp
    {
        public class ServerMessageLogger : IDispatchMessageInspector
        {
    
            public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
            {
                Console.WriteLine(request);
                return null;
            }
    
            public void BeforeSendReply(ref Message reply, object correlationState)
            {
    
                WebOperationContext ctx = WebOperationContext.Current;
                ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
                ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                if (ctx.IncomingRequest.Method == "OPTIONS")
                {
                    ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                    ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,POST,DELETE,OPTIONS");
                    ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
    
                }
    
    
            }
        }
        public class ClientMessageLogger : IClientMessageInspector
        {
            public void AfterReceiveReply(ref Message reply, object correlationState)
            {
    
            }
    
            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
    
                return null;
            }
        }
        [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = false)]
        public class CustContractBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
        {
            public Type TargetContract => throw new NotImplementedException();
    
            public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
            {
                return;
            }
    
            public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                clientRuntime.ClientMessageInspectors.Add(new ClientMessageLogger());
            }
    
            public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
            {
                dispatchRuntime.MessageInspectors.Add(new ServerMessageLogger());
            }
    
            public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
            {
                return;
            }
        }
    
    
    }

最后,将CustContractBehavior应用于服务:

如果问题仍然存在,请随时告诉我.

Feel free to let me know if the problem persists.

这篇关于Angular CORS飞行前请求导致400错误请求,但邮递员请求有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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