Click here to Skip to main content
12,065,045 members (43,154 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: WCF jQuery
Hi Friends

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

Service.cs
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
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
<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
<!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 18-Sep-12 1:11am
Edited 18-Sep-12 11:29am
v3
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

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.

 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.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Use JSONP instead of JSON for Cross-domain.

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

                                  }
                              });
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web03 | 2.8.160204.4 | Last Updated 18 Feb 2014
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100