【问题标题】:Setting Access-Control-Allow-Origin设置访问控制允许来源
【发布时间】:2015-11-03 15:07:27
【问题描述】:

我有简单的 .NET 网络服务:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    [WebMethod]
    public int Add(int x, int y)
    {
        return x+y;
    }


}

尝试从 Java 脚本调用:

<html>
<head>
    <title></title>



</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script>
        function ss() {

                var webserUrl = "http://localhost:41026/WebService.asmx";
                var soapRequest =
'<?xml version="1.0" encoding="utf-8"?> \
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \
  <soap:Body> \
    <Add xmlns="http://tempuri.org/"> \
      <x>int</x> \
      <y>int</y> \
    </Add> \
  </soap:Body> \
</soap:Envelope>';
                $.ajax({
                    type: "POST",
                    url: webserUrl,
                    contentType: "text/xml",
                    dataType: "xml",
                    data: soapRequest,
                    success: SuccessOccur,
                    error: ErrorOccur
                });

        };
        function SuccessOccur(data, status, req) {
            if (status == "success")
                alert(req.responseText);
        }
        function ErrorOccur(data, status, req) {
            alert(req.responseText + " " + status);
        }
    </script>
    <form>
    <input type="button" value="Click here" onclick="ss()">
    </form>
</body>
</html>  

出现错误:

XMLHttpRequest cannot load http://localhost:41026/WebService.asmx. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

据我所知,这是某种 CORS 问题。不幸的是我找不到解决方案。我必须做什么。在哪里以及如何解决问题 - 在服务器、客户端甚至浏览器中?

更新: 更新 web.config。现在看起来:

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
</configuration>

但现在我有内部服务器错误 500:

Remote Address:[::1]:41026
Request URL:http://localhost:41026/WebService.asmx
Request Method:POST
Status Code:500 Internal Server Error
Response Headers
view source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:1749
Content-Type:text/xml; charset=utf-8
Date:Tue, 03 Nov 2015 15:29:32 GMT
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcanNjcmlwdG5vbnNlbnNcV2ViU2l0ZTJcV2ViU2VydmljZS5hc214?=
Request Headers
view source
Accept:application/xml, text/xml, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:337
Content-Type:text/xml
Host:localhost:41026
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Request Payload
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">   <soap:Body>     <Add xmlns="http://tempuri.org/">       <x>int</x>       <y>int</y>     </Add>   </soap:Body> </soap:Envelope>

【问题讨论】:

    标签: javascript .net ajax web-services


    【解决方案1】:

    您需要在 web.config 中允许自定义标头,一个 la

    <system.webServer>
     <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
     </httpProtocol>
    </system.webServer>
    

    【讨论】:

    • 我已经根据你的建议更新了我的配置,但现在我有服务器错误 500。详细信息有问题正文。
    • 以上代码需要放在web.config文件的配置元素下。我认为它是导致 500 的语法错误。你能发布显示上面复制的 xml 的 web.config 内容吗(确保首先去除敏感值:))
    • 抱歉,没有看到您的编辑(在移动设备上并错过了),忽略我的最后评论
    • 好的,这需要一点点认识。如果您收到 500 服务器错误,则 CORS 请求被拒绝的原始问题已得到解决。你现在所经历的 500 是另一回事。
    • 是的,您的答案解决了 CORS。我通过在请求正文中修复 int \ int \ 解决了 500 个问题。
    猜你喜欢
    • 2020-05-14
    • 2011-09-18
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2017-12-15
    • 2016-08-18
    相关资源
    最近更新 更多