Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi Friends

I am getting bad request error while consuming WCF Service from jQuery. I have following so many articles...

Service.cs
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
using System.ServiceModel.Activation;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
	public string GetCustomers(string prefix)
	{
        List<object> customers = new List<object>();
        
        customers.Add(new
        {
            Id = 1,
            Name = "Person1"
        });
        customers.Add(new
        {
            Id = 2,
            Name = "Person2"
        });
        return (new JavaScriptSerializer().Serialize(customers));
        
    }
}

IService.cs
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

[ServiceContract]
public interface IService
{
	[OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    string GetCustomers(string prefix);
}

web.config
XML
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/> <!--Even I traied with IP Address-->
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
  </system.serviceModel>


HTMl File
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title> Demo 1</title>
		<script language="javascript" type="text/javascript" src="jquery.min.js"></script>
		<script language="javascript" type="text/javascript">
		$(document).ready(function(){
			 $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: 'http://152.125.253.121/MobileAppWebservices/Services/Service.svc/GetCustomers',
                data: '{"prefix": "test"}',
                processData: false,
                dataType: "json",
                success: function (response) {
                    var customers = eval(response.d);
                    var html = "";
                    $.each(customers, function () {
                        html += "<span>Name: " + this.Name + " Id: " + this.Id + "</span><br />";
                    });
                    alert(html)
                },
                error: function (err) {
                    alert(err.status + " - " + err.statusText);
                }
            });
		});
		</script>
	</head>
	<body>
	</body>
</html>


The code works as expected in Firefox. But in IE, Chrome and Opera throws exception like 400 Bad Request. I spent 2 days on this but not found any fix. (Its cross Domain hosted site in remote and accessed from the local host)

Please help me out?

Thanks
Posted
Updated 18-Sep-12 10:29am
v3

This question is quite old but this might help some one

I faced this problem while posting for a wcf service via jquery ajax.

My code used to work in firefox but not in IE & safari. (Didn't try any other browser. )

After checking network activity in IE & Firefox debuggers. Got the root cause.

C#
 contentType: "application/json; charset-uf8", //This Does not work in IE & Safari but works in firefox

contentType: "application/json; charset=UTF-8; charset-uf8 ",
//This works in IE, Firefox , Safari, Opera. have not tested it on chrome


Firefox somehow used to change the request headers internally.
 
Share this answer
 
Use JSONP instead of JSON for Cross-domain.

PHP
$.ajax({
                                   type: "POST",
                                 contentType: "application/json; charset=utf-8",
                                  url: "yourURL" +"/functionName",
                                   data: "{'num1': " + 3 + ", 'num2': " + 5 + "}"
                                 dataType: "jsonp",
                                  jsonp: 'jsonp_callback',
                                  success: function () {


                                  }
                              });
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900