Cors问题:通过JQuery消费WCF Rest服务

时间:2016-10-10 05:41:40

标签: jquery rest wcf cors

我一直在关注这个例子

Create and Consume WCF Restful Service Using jQuery

我收到以下错误:

XMLHttpRequest无法加载http://localhost:48839/EmployeeService.svc/GetEmployeeDetails/。对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' http://localhost:57402'因此不允许访问。响应的HTTP状态代码为404.

enter image description here

3 个答案:

答案 0 :(得分:0)

Tushar @,

快速谷歌搜索给了我这个: Enabling CORS header

要使您的呼叫成功,您可能必须在同一个域上托管服务和html页面。您正在从端口57402上的localhost获取html页面,并且您正尝试访问端口48839处的serice,因此您看到了此CORS问题。

您必须同时托管来自同一域和端口的服务端点和html页面,或者您必须将服务器上的访问标头列入白名单,如上面的链接中所述。

答案 1 :(得分:0)

您需要通过在项目中添加新的HttpModule来实现Cors支持。 为此,只需在项目中使用此代码https://gist.github.com/mmorton/4113849

答案 2 :(得分:0)

在服务项目中添加global.asax文件和

   protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }