繁体   English   中英

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

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

对于我的PHP应用程序,我需要使用Syncfusion Javascript字处理器 要使用默认文本实例化它,Syncfusion要求将此文本格式化为SFDT(一种JSON)。

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

此代码显示: 链接

使用.NET Core Package Syncfusion.EJ2.WordEditor.AspNet.Core ,我可以将doc(x)文件转换为sfdt格式。 因此,我使用Visual Pack 2017 for Mac创建了一个新的.NET Core Web Api应用程序。

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函数时,我在浏览器控制台中收到此错误:“跨源请求(阻止多源请求):”同源“策略不允许查询位于https:// localhost上的远程资源:5001 / Syncfusion / Import 。原因:CORS请求失败。“

我按照本教程和那些SO帖子Link1 Link2但它不起作用。 有解决这个问题的主意吗?

编辑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错误消息总是有点误导。

我们为“修复”它所做的是:

  1. 在firefox中打开https:// localhost:5001
  2. 您现在应该在Firefox中看到证书错误
  3. “信任”自签名证书/为其添加例外
  4. 再次尝试您的api调用。 它现在应该工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM