none
WCF service Ajax Post calling error RRS feed

  • Question

  • We are getting error when we call wcf service from the client end.Like As:

    "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response."

    Web config of WCF Odata Service is as:-

    <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehavior">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="EndpBehavior">
              <webHttp helpEnabled="true"/>
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <services>
          <service behaviorConfiguration="ServiceBehavior" name="IonicApp_Services.Service1">
            <endpoint name="webHttpBinding" address="" binding="webHttpBinding" contract="IonicApp_Services.IService1" behaviorConfiguration="EndpBehavior"/>
     </service>
        </services>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
        <standardEndpoints>
          <webScriptEndpoint>
            <standardEndpoint name="x" crossDomainScriptAccessEnabled="true" />
          </webScriptEndpoint>
        </standardEndpoints>
      </system.serviceModel>

    And Ajax calling code is like as:-

    <script type="text/javascript">
    
            var Type;
            var Url;
            var Data;
            var ContentType;
            var DataType;
            var ProcessData;
            //Generic function to call AXMX/WCF  Service        
            function CallService() {
                jQuery.support.cors = true;
                $.ajax({
                    type: Type, //GET or POST or PUT or DELETE verb
                    url: Url, // Location of the service
                    crossDomain: true, 
                    contentType: ContentType, // content type sent to server
                    data: Data, //Data sent to server
                    dataType: DataType, //Expected data format from server
                    //processdata: ProcessData, //True or False
    
                    headers: { 'X-Requested-With': 'XMLHttpRequest' },
                    success: function (msg) {//On Successfull service call
                        ServiceSucceeded(msg);
                    },
                    error: ServiceFailed// When Service call fails
                });
            }
    
            function ServiceFailed(result) {
                alert('Service call failed: ' + result.status + '' + result.statusText);
                Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
            }
    
            function WCFJSON() {
    
                var uesrid = "1";
                var Password = "1";
                Type = "POST";
                Url = "http://localhost:18730/Ionic_AppServices.svc/AuthenticateUser";
                Data = '{"username": "' + uesrid + '","Password": "' + Password + '"}';
                ContentType = "application/json, charset=utf-8";
                DataType = "json"; 
                CallService();
            }
    
            function ServiceSucceeded(result) {
    
                if (DataType == "json") {
    
                    resultObject = result.GetUserResult;
    
                    for (i = 0; i < resultObject.length; i++) {
                        alert(resultObject[i]);
                    }
                }
            }
            function ServiceFailed(xhr) {
                alert(xhr.responseText);
                if (xhr.responseText) {
                    var err = xhr.responseText;
                    if (err)
                        error(err);
                    else
                        error({ Message: "Unknown server error." })
                }
                return;
            }
    
            $(document).ready(
            function () {
                WCFJSON();
            }
            );
    
        </script>

    How to fix this error? thanks in advance.

    Thursday, May 26, 2016 8:03 AM

Answers

  • Hi Azeez Ansari,

    Based on your error message, it seems that it's cross domain issue, please add the following code on your 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;
    }

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Saturday, May 28, 2016 2:20 PM