简体   繁体   English

如何在 C# 服务器上启用 CORS?

[英]How to enable CORS on C# server?

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.我正在开发一个 web 应用程序,它有一个云服务器 (nodeJS) 和一个本地服务器 (C#) 来连接 PC 的串行端口。 The web page whose origin is the cloud server makes requests to the local server and gets this error来自云服务器的web页面向本地服务器发起请求,报此错误

Refused to connect to 'http://localhost:3100/connection' because it violates the document's Content Security Policy.

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).我使用 CORS 库在 python 中解决了这个问题,但我仍然想在 C# 中解决这个问题(因为性能原因)。 This is my server in C#这是我在 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();
    }

Is there any library I could use with SimpleHttp?有没有我可以与 SimpleHttp 一起使用的库? I am also using CefSharp to render the webpage.我也在使用 CefSharp 来呈现网页。 Is there any way to configure chromium web browser to ignore CORS errors?有没有办法配置铬 web 浏览器忽略 CORS 错误?

CORS problem should be solved in server side, there must be a keyword or something that you should set your "project configuration files" CORS 问题应该在服务器端解决,必须有一个关键字或者你应该设置“项目配置文件”的东西

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://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api只是快速谷歌搜索,请检查更多信息: https://docs.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.第一个为所有控制器启用缓存,而第二种方法是基于 controller 的方法,在这种情况下允许仅来自给定来源的核心请求,如果您想允许所有来源,则应将“*”设置为值。

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

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