在 Firefox for WCF POST REST 请求中出现 CORS 错误

Getting CORS error in Firefox for WCF POST REST request

我在 Firefox 中收到 WCF POST 请求的 CORS 错误。此代码在 Edge 和 Chrome 中运行良好。该错误仅在 Firefox 中出现。此外,仅当我使用数据参数集和 contentType 设置为 "Application/Json; charset=utf-8" 进行调用时,才会在 Firefox 中看到该错误。如果将 contentType 更改为 "text/plain",我会收到“400 错误请求”错误。我的代码如下:

WCF 中的选项处理器:

[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
    public void GetOptions()
    {
        if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "https://localhost:5001");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS,HEAD,PUT,DELETE");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Max-Age", "1728000");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "x-requested-with, Content-Type, origin, authorization, accept, client-security-token");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Credentials", "true");
        }
    }

我调用的post方法:

 [WebInvoke(UriTemplate = "GetAttachmentsPost1", RequestFormat = WebMessageFormat.Json,          ResponseFormat = WebMessageFormat.Json, BodyStyle =WebMessageBodyStyle.Bare, Method = "POST")]
    public void GetAttachmentsPost1( teststr teststr1)
    {

        string  str = "abc";

    }
[DataContract]
  public class teststr
{ 
[DataMember]
public string teststr1 { get; set; }

}

对服务的 AJAX 调用:

 $.ajax({

            url: "http://127.0.0.1:5555/MyWCFService/GetAttachmentsPost1",

            type: "POST",

            data: JSON.stringify({ 'teststr1':'abc'} ),

            xhrFields: {
                withCredentials: true
            },
            contentType: "application/json; charset=utf-8",


            crossDomain: true,
            dataType: "JSON",
            processData: true,
            error: function (data) {

            },
            success: function (data) {

            },
            statusCode: {
                404: function () {
                    //     page not found
                }
            },
            complete: function (data) {

            },
        });

正如我上面提到的,它在 Edge 和 Chrome 中运行良好,但仅在 FF 中失败。在 Edge 和 Chrome 中,预检调用是对 OPTIONS 进行的,但在 FF 中,调用不会进行。

感谢任何帮助。

谢谢。

这个问题发生在 Firefox 上,因为我的 Web 应用程序是 HTTPS,而我的 WCF 服务是 HTTP。对于 Firefox,这是一个 CORS 问题:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed

解决方案在于 运行 WCF 服务也在 https 上。