-1

I am developing a web app that has a cloud server (nodeJS) and a local server (C#) to interface the serial port of the PC. The web page whose origin is the cloud server makes requests to the local server and gets this error

Access to fetch at 'http://localhost:3100/connection' from origin 'http://cloud.tissuelabs.com' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`

I tried adding headers to the request

'headers': {'Access-Control-Allow-Origin': '*'}

but it doesn`t solve my problem. I solved this problem in python using CORS libraries, but I still want to solve this problem in C# (because of performance). This is my server in C#

private void InitializeServer()
    {
        myServer = new Thread(Server);
        myServer.Start(this);
    }

    private void Server(Object _obj)
    {
        Route.Add((req, props) => req.Url.LocalPath.ToLower().EndsWith("connection"),
            (req, res, args) =>
        {
            if (req.HttpMethod == "GET")
            {
                Regex rx = new Regex(@"port=(?<word>\w+)",
                    RegexOptions.Compiled | RegexOptions.IgnoreCase);
                MatchCollection matches = rx.Matches(req.Url.Query);
                if (matches.Count > 0)
                {
                    bool on = true;
                    bool printing = true;
                    WriteLog($"GET {req.Url.LocalPath + req.Url.Query}");
                    WriteLog($"{matches[0].Groups["word"].Value}");
                    string output = "{" + $"'on':{on}, 'printing':{printing}, 'queue': {10}" + "}";
                    res.AsText(output);
                }
                else
                {
                    WriteLog($"GET {req.Url.LocalPath}");
                    string[] ports = SerialPort.GetPortNames();
                    string output = "{'ports':[";
                    foreach (string port in ports)
                    {
                        output += "{" + $"'port':'{port}', 'name':'{port}'" + "}";
                    }
                    output += "]}";
                    res.AsText(output);
                }
            } 
            else if (req.HttpMethod == "POST")
            {
                WriteLog("POST /connection");

                Stream stream = req.InputStream;
                StreamReader sr = new StreamReader(stream);
                JsonSerializer serializer = new JsonSerializer();
                Connection con = (Connection)serializer.Deserialize(sr, typeof(Connection));
                connectSerial(con.port);

                res.AsText("{'ok': True}");
            } 
            else if (req.HttpMethod == "DELETE")
            {
                WriteLog("DELETE /connection");
                res.AsText("OK");
            }
        });

        
        

        HttpServer.ListenAsync(3100, System.Threading.CancellationToken.None, Route.OnHttpRequestAsync)
        .Wait();
    }

When I add access control allow origin to header, it works on firefox, but not on Chrome

res.AddHeader("Access-Control-Allow-Origin", "*");

Is there any library I could use with SimpleHttp? I am also using CefSharp to render the webpage. Is there any way to configure chromium web browser to ignore CORS errors?

  • Any reason you can't add another else if clause `else if (req.HttpMethod == "OPTIONS")`? If it is OPTIONS, then add the `Access-Control-Allow-Origin` header to response? – peinearydevelopment Jan 18 '22 at 18:57
  • 1
    There's no such thing as a "C# server" per se. It sounds like *MAYBE* you might be using [Microsoft Web API](https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api)? Exactly *HOW* you configure CORS depends in part on your library (e.g. ASP.Net MVC vs Web API) and .Net version (e.g. .Net 4.x vs ASP.Net Core vs. .Net 6). This might help: [Enable cross-origin requests in ASP.NET Web API 2](https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api) – paulsm4 Jan 18 '22 at 18:58
  • You can take a look at this answer and see if it works for your case: https://stackoverflow.com/a/70665455/1807452 – Rahul Sharma Jan 18 '22 at 20:02
  • The error message clearly mentions a CSP violation. CSP != CORS. What is the CSP of the page that issues the request? Where is it set? – jub0bs Jan 18 '22 at 20:22
  • @peinearydevelopment I tried adding headers to the response. But even when I GET request, I still get CORS error. I also tried to add else if req.httpmethod == "OPTIONS" without success – Lucas Miyazaki Jan 19 '22 at 14:34

1 Answers1

0

CORS problem should be solved in server side, there must be a keyword or something that you should set your "project configuration files"

I found

namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

and

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

just quick googling, please check for further information : https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

The first one enables cache for all of your controllers whereas the second method is controller based which in this case allows core request that only comes from given origins, if you'd like to allow for all origins you should set "*" as value.