WCF Call Error : Access-Control-Allow-Origin Error and Cross Domain Header Issue

To Resolve JSON based WCF REST Service which gives below error and please follow below steps.

Add in Global.aspx

		protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.Flush();
            }
        }

Add in Web.Config

  <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>  

Ajax Call Function

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">

        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "http://localhost:1214/FB.svc/GetFaceBookPost",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert(data)
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });

</script>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s