0

I am trying to consume WCF service in angular . but getting error like this.

XMLHttpRequest cannot load http://localhost:50961/abc.svc/test1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3953' is therefore not allowed access.

please help me out .

Thanks.

1 Answers1

0

You need to enable CORS on your WCF services by adding the relevant HTTP headers to your response. This is because your current application's domain localhost:3953 doesn't match your ajax request's domain localhost:50961 and in this case browser will automatically send a preflight request to server asking if the server supports CORS. In fact it asks for two HTTP headers: Access-Control-Request-Method and Access-Control-Request-Headers.

So to enable CORS first add a Global.asax file in your wcf project's root address and put the following code in the related .cs file:

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)
    {

    }
}

If you don't know the origin, you can use * instead of http://foo.com as origin. For more thorough explanation refer to this link.

Ashkan
  • 3,322
  • 4
  • 36
  • 47