Cors 请求因 .Net Core API 和 PHP/JS 客户端应用程序(Syncfusion 字处理器)而失败

Cors Request failed with .Net Core API and PHP/JS Client App (Syncfusion Word Processor)

对于我的 PHP 应用程序,我需要使用 Syncfusion Javascript Word Processor。为了使用默认文本对其进行实例化,Syncfusion 要求将该文本格式化为 SFDT,一种 JSON.

//SFDT Example
"sections": [
    {
        "blocks": [
            {
                "inlines": [
                    {
                        "characterFormat": {
                            "bold": true,
                            "italic": true
                         },
                         "text": "Hello World"
                     }
                 ]
             }
         ],
         "headersFooters": {
         }
     }
 ]

此代码显示:Link

使用 .NET Core 包 Syncfusion.EJ2.WordEditor.AspNet.Core,我可以将 doc(x) 文件转换为 sfdt 格式。所以我用这个包创建了一个新的.NET Core Web Api 应用 Visual Studio 2017 For Mac。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.DocumentEditor;

namespace SyncfusionConverter.Controllers
{
    [Route("api/[controller]")]
    public class SyncfusionController : Controller
    {

        [AcceptVerbs("Post")]
        public string Import(IFormCollection data)
        {
            if (data.Files.Count == 0)
                return null;
            Stream stream = new MemoryStream();
            IFormFile file = data.Files[0];
            int index = file.FileName.LastIndexOf('.');
            string type = index > -1 && index < file.FileName.Length - 1 ?
            file.FileName.Substring(index) : ".docx";
            file.CopyTo(stream);
            stream.Position = 0;

            WordDocument document = WordDocument.Load(stream, GetFormatType(type.ToLower()));
            string sfdt = Newtonsoft.Json.JsonConvert.SerializeObject(document);
            document.Dispose();
            return sfdt;
        }

        internal static FormatType GetFormatType(string format)
        {
            if (string.IsNullOrEmpty(format))
                throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
            switch (format.ToLower())
            {
                case ".dotx":
                case ".docx":
                case ".docm":
                case ".dotm":
                    return FormatType.Docx;
                case ".dot":
                case ".doc":
                    return FormatType.Doc;
                case ".rtf":
                    return FormatType.Rtf;
                case ".txt":
                    return FormatType.Txt;
                case ".xml":
                    return FormatType.WordML;
                default:
                    throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
            }
        }
    }
}

我发出 Ajax 请求以我的 doc(x) 文件作为参数调用此 .Net 方法。

function loadFile(file) {
    const ajax = new XMLHttpRequest();
    const url = 'https://localhost:5001/api/Syncfusion/Import';
    ajax.open('POST', url, true);
    ajax.onreadystatechange = () => {
        if (ajax.readyState === 4) {
            if (ajax.status === 200 || ajax.status === 304) {
                // open SFDT text in document editor
                alert(ajax.status);                                                          
             }else{
                 alert(ajax.status);
             }
         }else{
              alert(ajax.readyState);
         }
     };
     let formData = new FormData();
     formData.append('files', file);
     ajax.send(formData);
}

执行 loadFile 函数时,我在浏览器的控制台中收到此错误:"Cross-Origin Request (Blocking of a Multi-Origin Request): the "Same Origin" policy does not allow to consult the remote resource located on https://localhost:5001/Syncfusion/Import。原因:CORS 请求失败。 “

我关注 this tutorial and those SO posts 但它不起作用。有解决这个问题的想法吗?

编辑 1:我的代码似乎在 Safari 和 Chrome 上工作,但在 Firefox 上不起作用。

编辑 2:Startup.cs

namespace SyncfusionConverter
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(setup => setup.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
        }));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseCors("CorsPolicy");
        app.UseHttpsRedirection();
        app.UseMvc();
    }
}
}

您的代码看起来不错。我的猜测是 firefox 与您的 asp.net 核心应用程序的自签名开发证书有问题。我们过去有过几次这种情况,firefox 错误消息总是有点误导。

我们对 "fix" 所做的是:

  1. 在 firefox
  2. 中打开 https://localhost:5001
  3. 您现在应该会在 firefox 中看到证书错误
  4. "Trust"自签名证书/为其添加例外
  5. 再试一次 api 呼叫。它现在应该可以工作了