WCF REST服务模板40(CS)跨域错误 [英] WCF REST Service Template 40(CS) Cross domain error
问题描述
您好我在使用(WCF REST服务模板40(CS))一个WCF REST服务。我设法得到它返回JSON响应。该项目在运行时工作正常。但是,当我试图做一个以AjaxCall的从浏览器的服务,我得到错误:
Hi I have a WCF Rest service using ( WCF REST Service Template 40(CS)). I have managed to get it to return Json response. It is working fine when the project is run. But when I try to make a Ajaxcall to the service from the browser, I am getting Error:
跨域请求阻止:同源策略不允许阅读
在 http://192.168.0.70:8001/Service/test
远程资源。
这可以由资源移动到相同域或固定
使CORS。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
http://192.168.0.70:8001/Service/test
. This can be fixed by moving the resource to the same domain or enabling CORS.
和AJAX调用:
$.ajax({
type: "POST",
url: "http://192.168.0.70:8001/Service/test",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
var Tabels = msg.d;
alert('success');
}
});
下面是在web.config:
Here is the web.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConString" connectionString="SERVER=localhost;DATABASE=fabapp;UID=root;PASSWORD=;"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
我尝试添加crossDomainScriptAccessEnabled =真,但是当我这样做,该服务不会在本地主机的工作也。我得到这样的:
I tried adding crossDomainScriptAccessEnabled="true" but when I do that the service does not work on the localhost also. I get this:
跨域
服务。
Cross domain javascript callback is not supported in authenticated services.
什么我需要在web.config文件来改变?
Anything I need to change in web.config file?
推荐答案
实事求是地讲,我不得不面对这个问题,我已经一步检查的WebAPI,并需要同样的努力,当我分析。所以我不得不解决这个问题与WCF CORS
。我会尽量在短期解释。开始了。当您从JS code使用WCF请求与CrossOrigin,就像存在于不同的领域,并从JS,你尝试做 PUT
或 POST
的要求,第一个浏览器发送一个 OPTION
要求 405 HTTP状态
,看看这个域名在允许列表中,那么如果你的 WCF
到选项
要求作出回应,将与标头值所需的响应,那么浏览器就会再做一个 POST
或 PUT
请求(这曾经浏览器发出更早),并预期它会工作。
Practically speaking , i had faced this issue, i have gone one step further to check WebAPI, and same effort was required, when i analysed. So i had to fix this CORS with WCF
. I will try to explain in short. Here we go. When you access WCF request with CrossOrigin, like from JS code existing in different domain, and from JS , you try to do PUT
or POST
request, 1st browser sends an OPTION
request 405 HTTP Status
, to see if this domain is in allowed list, then if your WCF
respond to OPTIONS
request, sends required response with header value, then browser will again do a POST
or PUT
request ( which ever browser issued earlier), and it will work as expected.
请注意:你不能发送(访问控制允许来源,*)
,因为有一个安全功能,所需任务域命名上市访问控制允许来源
而不是 *
。
NOTE: you can not send ("Access-Control-Allow-Origin", "*")
, because, there is a security feature , that mandates required domain name to be listed in Access-Control-Allow-Origin
instead of *
.
有关更多信息 -
<一个href=\"http://social.msdn.microsoft.com/Forums/ro-RO/5613de55-2573-49ca-a389-abacb39e4f8c/wcf-rest-service-post-cross-domain-not-working?forum=wcf\" rel=\"nofollow\">http://social.msdn.microsoft.com/Forums/ro-RO/5613de55-2573-49ca-a389-abacb39e4f8c/wcf-rest-service-post-cross-domain-not-working?forum=wcf
从实践经验来看,我曾尝试 *
在这头,它不工作。如果你不相信我,继续和尝试。
From practical experience, i have tried *
in that header, it was not working. If you don't believe me, go ahead and try .
最后,code为以下。你需要把这个的Global.asax
。
Finally the code is following. You need to put this in Global.asax
.
protected void Application_BeginRequest(object sender, EventArgs e)
{
String domainname = HttpContext.Current.Request.Headers["Origin"].ToString();
if (IsAllowedDomain(domainname))
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", domainname);
String allowedmethods = "POST, PUT, DELETE, GET";
String headers = HttpContext.Current.Request.Headers["Access-Control-Request-Headers"].ToString();
String accesscontrolmaxage = "1728000";
String contenttypeforoptionsrequest = "application/json";
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", allowedmethods);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", headers);
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", accesscontrolmaxage);
HttpContext.Current.Response.AddHeader("ContentType", contenttypeforoptionsrequest);
HttpContext.Current.Response.End();
}
}
private bool IsAllowedDomain(String Domain)
{
if (string.IsNullOrEmpty(Domain)) return false;
string[] alloweddomains = "http://192.168.0.70:8001"; // you can place comma separated domains here.
foreach (string alloweddomain in alloweddomains)
{
if (Domain.ToLower() == alloweddomain.ToLower())
return true;
}
return false;
}
这篇关于WCF REST服务模板40(CS)跨域错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!