如何使用Web Service和jQuery Ajax启用CORS [英] How to enable CORS with Web Service and jQuery Ajax

查看:103
本文介绍了如何使用Web Service和jQuery Ajax启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WebService(.asmx)页面,其中包含许多我想从其他网页运行的函数。我想使用ajax来调用函数的网页来自与Web服务不同的来源。当我尝试以下ajax调用时:

I have a WebService (.asmx) page with many functions I want to run from another webpage. The webpages I want to use ajax in to call the functions are from a different origin than the web service. When I try the following ajax call:

$.ajax({
        type: "POST",
        url: "http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList",
        crossDomain: true,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'filterID': 0
        }),
        dataType: "json",
        success: function (data)
        {
            data = JSON.parse(data.d);
            console.log(data);
        }
    });

我收到以下错误:


XMLHttpRequest无法加载
http://192.168。 18.218 /网站/网页/ DBQuery.asmx / GetTestList 。响应
预检请求未通过访问控制检查:否
'Access-Control-Allow-Origin'标头出现在请求的
资源上。因此,不允许访问 http:// localhost
响应的HTTP状态代码为404.

XMLHttpRequest cannot load http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

我可以使用在浏览器上作为网址提供的确切链接与托管Web服务的机器相同,一切都按预期工作。使用来自Internet explore 11或边缘的这个ajax调用也很好,但是当从google chrome运行命令时,它会给出上述错误。

I can use that exact link provided as the url on a browser on the same machine as where the web service is being hosted and everything works as expected. Using this ajax call from internet explore 11 or edge works fine as well, but when running the command from google chrome it gives the above error.

读取它似乎是我的Web服务没有在CORS的响应数据包中添加正确字段的问题,因此谷歌浏览器设置捕获并抛出一个错误。我尝试使用用于Web API的代码来启用CORS(参见下面的代码块)。

Reading up it seems like this is an issue with my web service not adding in the right fields to its response packets for CORS, so the google chrome setting catches it and throws an error. I have tried to code used for web API's to enable CORS (see the following code block).

public static void Register(HttpConfiguration config)
    {
        //TODO: determine acceptable origins
        var corsAttr = new EnableCorsAttribute("*", "*", "*"); //accept all origins, headers, and methods
        config.EnableCors(corsAttr); //enable cross origin requests
    }

这似乎不起作用,我找不到使用Web服务而不是Web API解决此问题的文档。如何修复Web服务和/或ajax调用以正确启用CORS?

This did not seem to work and I cannot find documentation for this issue using web services instead of web APIs. How do I fix the web service and or ajax calls to enable CORS correctly?

编辑
将以下代码行添加到Web配置文件可修复问题没有添加标题的CORS部分:

EDIT Adding the following lines of code to the web config file fixes the issue with the CORS portion of the header not being added:

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
      </customHeaders>
    </httpProtocol>

但是,我仍然收到404错误。在托管Web服务的计算机上测试ajax调用,ajax正常工作并且符合预期。但是当它跨越原点运行时,我得到404错误。

However, I still am getting a 404 error. Testing the ajax call on the machine hosting the web service, the ajax works correctly and as expected. However when running it cross origin, I get the 404 error.

推荐答案

即使将自定义标题添加到Web配置后404错误仍然存​​在这最终是由于标题仍未完全正确或ISAPI使用OPTIONS动词拦截数据包并导致一些我从未弄清楚确切原因的问题。我的解决方案是删除对Web配置的更改,并使用以下代码添加Global asax文件:

Even after adding the custom headers to the web config the 404 error remained. This ended up being due to the header still not being fully correct or ISAPI intercepting packets with the OPTIONS verb and causing some issues I never figured out the exact cause. My solution was to remove the changes to the web config and add a Global asax file with the following code:

<%@ Application Language="C#"%>

<script RunAt="server">
    void Application_BeginRequest(object sender, EventArgs e)
    {
        var context = HttpContext.Current;
        var response = context.Response;

        // enable CORS
        response.AddHeader("Access-Control-Allow-Origin", "*");

        if (context.Request.HttpMethod == "OPTIONS")
        {
            response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            response.End();
        }
    }
</script>

这可确保数据包具有正确的标头。你必须删除我在我的问题中提到的web配置的部分,因为它会添加两次,这将导致ajax调用失败。

This makes sure the packets have the right headers. You have to remove the pieces of the web config I mentioned in my question as it will add them twice which will cause the ajax call to fail as well.

这篇关于如何使用Web Service和jQuery Ajax启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆