如何在Angular JS中调用wcf服务
问题描述:
我试图在角度中使用WCF服务。但得到这样的错误。如何在Angular JS中调用wcf服务
XMLHttpRequest无法加载http://localhost:50961/abc.svc/test1。请求的资源上没有“Access-Control-Allow-Origin”标题。因此'Origin'http://localhost:3953'不允许访问。
请帮我一把。
谢谢。
答
您需要在您的WCF服务上启用CORS,方法是在响应中添加相关的HTTP标头。这是因为您的当前应用程序的域localhost:3953
与您的ajax请求的域localhost:50961
不匹配,在这种情况下,浏览器会自动向服务器发送预检请求,询问服务器是否支持CORS。实际上,它要求两个HTTP头:访问控制请求方法和访问控制请求头。
所以使CORS先在你的WCF项目的根地址添加Global.asax文件,并把下面的代码在有关.cs文件:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
string sessionID = Session.SessionID;
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var ctx = HttpContext.Current;
ctx.Response.AddHeader("Access-Control-Allow-Origin", "http://foo.com");
if (ctx.Request.HttpMethod != "OPTIONS") return;
ctx.Response.AddHeader("Cache-Control", "no-cache");
ctx.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
ctx.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
ctx.Response.AddHeader("Access-Control-Max-Age", "1728000");
ctx.Response.End();
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
如果你不知道的起源,你可以使用*
而不是http://foo.com
作为原点。有关更详尽的解释,请参阅link。