Thibault
Thibault

Reputation: 23

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

For my PHP app, I need to use the Syncfusion Javascript Word Processor. To instantiate it with a default text, Syncfusion asks that this text be formatted in SFDT, a kind of JSON.

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

This code show this : Link

With a .NET Core Package Syncfusion.EJ2.WordEditor.AspNet.Core, I can convert a doc(x) file to sfdt format. So I create a new .NET Core Web Api App with Visual Studio 2017 For Mac with this package.

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.");
            }
        }
    }
}

I make a Ajax request to call this .Net method with my doc(x) file as parameter.

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);
}

When loadFile function is executed, i got this error in browser's console : "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. Reason: CORS request failed."

I follow this tutorial and those SO posts Link1 Link2 but it doesn't work. Any idea to solve this problem ?

Edit 1 : It seems that my code work on Safari & Chrome, but doesn't work on Firefox.

Edit 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();
    }
}
}

Upvotes: 0

Views: 302

Answers (1)

Andre Kraemer
Andre Kraemer

Reputation: 2761

Your code looks fine. My guess is that firefox has an issue with your self signed development certificate of your asp.net core application. We had this several times in the past and the firefox error message were always a bit misleading.

What we did to "fix" it was:

  1. Open https://localhost:5001 in firefox
  2. You should see a certificate error in firefox now
  3. "Trust" the self signed certificate / add an exception for it
  4. Try your api call again. It should work now

Upvotes: 0

Related Questions