0

我正在尝试在网页和 ac# 套接字之间交换数据。c# 套接字在本地主机上运行。该网页在服务器上运行并指向本地主机。

当网页向 c# 套接字发送 Get 请求时,会显示跨域错误。

XMLHttpRequest cannot load http://localhost:12345/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.3:9000' is therefore not allowed access.

这是网页上运行的 JS(Angular)。

var serviceUrl = 'http://localhost:12345';
var service = $resource(
   serviceUrl,{}, {
       getCard: {
           method: "GET"
       }
   }
);

service.getCard();

这是来自 c# 控制台应用程序的代码的一部分。

private static void Send(Socket handler, String data)
{
    // Convert the string data to byte data using ASCII encoding.
    byte[] byteData = Encoding.ASCII.GetBytes(data);

    // Begin sending the data to the remote device.
    handler.BeginSend( byteData
                     , 0
                     , byteData.Length
                     , 0
                     , new AsyncCallback(SendCallback)
                     , handler                      
                     );

如何将标头信息添加到响应中。标题必须是: Access-Control-Allow-Origin: * 当我将它添加到字符串前面时它不起作用。

4

1 回答 1

0

服务页面时必须添加标头,而不是来自套接字响应。它只是一个普通的旧 HTTP 标头。

如果您使用 IIS 为您的网页提供服务,请在发送页面之前执行以下操作:

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
于 2014-08-24T10:06:54.203 回答