JQuery to asmx fails on Windows 2008 R2 SP1 - asp.net

Since the installation of SP1 we are facing problems in calling asmx pages from JQuery client code.
IIS is pointing the JQuery post call to his default 404 page.
We did a roleback of our environment to assert this issue is caused by SP1 and tests confirm it.
Waiting for a fix #MS
Technologies used:
ASP.Net 4.0 -
JQuery -
IIS 7.5 -
Windows 2008 R2 SP1
--Bart
Code Sample calling (front-end):
// Code to load vars...
$.ajax({
type: "POST",
url: "/Handlers/ProductRating.asmx/RateProduct",
data: "{'uniqueId':'" + uniqueId + "','productId':'" + productId + "','points':" + points.toString() + ",'showOwnScore':" + showOwnScore.toString() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert('success');
},
failure: function(msg) {
alert('something went wrong');
}
});
}
Code back-end:
[ScriptService]
public class ProductRating : System.Web.Services.WebService
{
[WebMethod(EnableSession=true)]
public RateProductResponse RateProduct(Guid uniqueId, Guid productId, int points, bool showOwnScore)
{
//Implementation
}
Snapshot1 : With SP1:
http://img812.imageshack.us/i/capture2r.png/
Snapshot2 : Without SP1:
http://img190.imageshack.us/i/capture1qx.png/

I was able to get this working with the following addition to my web.config
I saw another site that suggested clearing the handlers, but that made everything way worse. With this update, I was able to call my web services once again.
<system.webServer>
<handlers>
<add name="AsmxRoutingHandler" verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</handlers>
</system.webServer>

I had the same problem.
Create a Web.Config file containing the following lines:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.web>
<httpHandlers>
<clear />
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add path="*" verb="GET,HEAD,POST" type="System.Web.DefaultHttpHandler" validate="True" />
</httpHandlers>
</system.web>
</location>
</configuration>
Copy this into the directory(s) where you serve out your affected scripts, and restart your web server.
These lines will override your preferred HttpHandlers and set it to use the default handlers instead.
Good luck!

Judging by your screenshots, that seems an awful lot like a URL rewriting issue. Does your site have any overly-greedy URL rewrite rules at the IIS level that could be 302 redirecting /Handlers/ProductRating.asmx/RateProduct?
If you do have rewrite rules, can you try disabling them temporarily to see if that fixes the ASMX issue?

Related

jQuery Ajax to asp.net asmx web service throws Request format is invalid: application/json

I have jquery call an asp.net webservice with an integer.
On our legaacy application which was ported to .net 4.0 I cannot get this call to work.
I can call a method which has no parameters but sending data to the web method returns the following error:
System.InvalidOperationException: Request format is invalid: application/json; charset=UTF-8.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
I created exactly the same code in a blank project and it worked fine. I couldnt see anything in the web.config that the blank project added that would make a difference.
the Jquery Code
$.ajax({
type: "POST",
url: "/WebService1.asmx/Test",
data: JSON.stringify({"code": 1234}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
My Web Service Code
<ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class WebService1
Inherits WebService
<WebMethod()>
Public Function Test(ByVal code As Integer) As String
Return "success"
End Function
<WebMethod()>
Public Function Hello() As String
Return "hello"
End Function
End Class
Web Config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
</appSettings>
<connectionStrings>
</connectionStrings>
<system.web>
<httpRuntime enableVersionHeader="false" />
<httpCookies httpOnlyCookies="true" requireSSL="false" lockItem="true" />
<trace enabled="false" pageOutput="true" requestLimit="40" localOnly="true"/>
<httpModules>
</httpModules>
<compilation debug="true" strict="true" explicit="true" targetFramework="4.0">
</compilation>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
</pages>
<authentication mode="Forms">
<httpHandlers>
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
</modules>
<handlers>
</handlers>
<httpErrors errorMode="Custom" >
</httpErrors>
</system.webServer>
</configuration>
DOH, I was working in the wrong web.config.
Like a lot of questions on SO the solution was to add the following.
<system.webServer>
<handlers>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</handlers>
</system.webServer>
I had the same problem and ending up running this command...
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Note that you will need your command prompt in Administrator mode for it to work.

ASP.NET Ajax client-side framework failed to load. when put the ScriptManager on a blank page

I have an error Microsoft JScript runtime error: ASP.NET Ajax client-side framework failed to load. on a blank page using masterpage
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="True">
</asp:ScriptManager>
</form>
</body>
</html>
This is what it render it the end
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form method="post" action="WebForm2.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjE2OTgwNTY5ZGTfWA/dEX85PXBlbkKsVxeLKyIn+mJQ9piW5cbeNE+qww==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="http://ajax.microsoft.com/ajax/4.0/2/WebForms.js" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=6x_aX-LOcgUU-O_K6nM7ST5ViC_naT1e4_j-CY35ASRLpcKYpiapwTARuePHvx3llP-Xhl_AG_ubpM1BzkM5iyn9ThB3m7lmXKvkck0cxTcYiT-VbeKgamKxp9EwxBUyIQN6sSCU9SQm3tMtmzQWRg2&t=ffffffffbad362a4" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/ScriptResource.axd?d=khKEuZ4oUqBYvQxJ1ISpPVIW8_AWWc907q5_v74DI2ruWKTJpldq2osxPkAZ__hffe1Q6HTQUyTbL3Q1mD6MX7V65O5ibxKwb4NvN6ycdZ8vEJ-bz51MO-8uoaP2xioK6npm5n8vldI1d0sOCnH6yw2&t=ffffffffbad362a4" type="text/javascript"></script>
<div>
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1', 'form1', [], [], [], 90, '');
//]]>
</script>
</form>
</body>
</html>
The problems might be that i used to have AjaxControlToolkit in my project but later i use jquery instead. so somewhere in the project might try to add Ajaxcontroltoolkit which i can't find it. i don't know how to fix this error. i have tried to add bin file of ajaxcontroltoolkit back but it seems to not work.
this solution works for me:
The error on client was:
SCRIPT5022: ASP.NET Ajax client-side framework failed to load.
SCRIPT5009: 'Sys' is undefined
After many time to mining the websites, and more solutions, i solve the problem:
the solution for .NET 4.0 is:
Set EnableCdn property of script manager to true, Like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true">
Next Solution and Better Solution is:
add this handler to your web.config
<system.webServer>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
Sys undefined means that you're not getting the client side files loaded on your browser.
Solution 1:
<add verb="GET"
path="ScriptResource.axd"
type="Microsoft.Web.Handlers.ScriptResourceHandler"
validate="false"/>
Solution 2: If you don't have this, add this too under <assemblies>
<add assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Solution3: If that doesn't work too, try deleting files from your "bin" folder and rebuild the solution and clear the cache of your browser.
Solution 4: Add this to your web.config
<location path="ScriptResource.axd">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
for telerik web resources use this code:
<location path="Telerik.Web.UI.WebResource.axd">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
I had enabled WebForms Routing and forgot to add the exception for resources:
routes.Ignore("{resource}.axd/{*pathInfo}");
Another possible cause is script combining/compression in IE 8 & 9. In web.config at the top level (within Configuration), put
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>
On your ToolKitScriptManager put CombineScripts=False, e.g.
<asp:ToolkitScriptManager runat="server" CombineScripts="False">
</asp:ToolkitScriptManager>
see http://robmzd.blogspot.com/2010/02/invalid-character-error.html which is where I figured out the problem
Add EnableScriptCombine="False" to your RadScriptManager as follows:
<telerik:RadScriptManager ID="RadScriptManager1" EnableScriptCombine="False" runat="server" />
I had this problem when I moved my forms to a new server. I spent hours to find the solution.
The problem was that the new server has ASP.NET 4.0 and my web.config was ASP.NET 3.5. So I made a new web.config and everything is ok now.
Simply add the <handlers> section as shown below in your web.config within <system.webServer> and this will fix the problem in no time.
<system.webServer>
.
.
.
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
For me it was the problem with Global.asax code,
Just check below condition before validating session in Application_PreRequestHandlerExecute
Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "SCRIPTRESOURCE.AXD"
Functional code is shown below,
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
if ((Request.Path != Constants.DebugLoginUrl) &&
(Request.Path != Constants.SessionTimeOut) &&
(Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "TRACE.AXD") &&
(Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "SCRIPTRESOURCE.AXD"))
{
// to prevent check of HTTP HANDLER FLUSH - Session State is Invalid
if (HttpContext.Current.Session != null)
{
if (Session[Constants.personId] == null)
{
//your code
}
else
{
Response.Redirect(Constants.SessionTimeOut);
}
}
}
In my case the Ajax loading error occurred only if I reloaded the page, not when the page was loaded for the first time.
Looking at the content in the tag in Site.Master, I noticed that only some of the items had Path attribute set. So, I updated MsAjaxBundle to this: and the problem went away. I also had to modify the WebFormsBundle the same way and now reloading the page works.
What worked for me was to download ASP.NET Ajax from Microsoft.
You might also need to explicitly browse for the correct dll version when you add reference e.g.
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.Web.Extensions.dll
I set Application Pool as ASP.NET 4.0 Classic during installation.
well i just changed RadScriptManger to Simple asp:ScriptManager and it works
Before:
<telerik:RadScriptManager ID="RadScriptManager1" EnableCdn="true" runat="server" />
After
<asp:ScriptManager ID="scrReg" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
Hope it helps
And here's another cause. I installed MySQL Connector/net 6.9.5. Later I started getting the dreaded 'sys undefined' for everything in some, but not all, projects in IE. Many, many hours later I tried Chrome and Opera and the first page opened fine but on post back all the session variables had vanished. That's when the penny finally dropped - Connector/net must have set itself up the session state provider but I had nothing for session state in web.config for the failing projects. Sessionstate inproc fixed it immediately. At least I think that's what happened...
In my case, I had ended up with the mentioned handlers in <httpHandlers> as well as in <handlers>.
Removing the <httpHandlers> section fixed it.
After adding System.Web.MVC reference to my ASP.NET and added default route in global.asax
i.e.
RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "new", action = "Index", id = "" });
}
Started getting the error
Added below line to global.asax.cs to resolve it
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
For anyone working with the Visual Studio 2015 ASP.NET 4.5 WebForms Web Application project template which bundles the ASP.NET AJAX scripts:
https://stackoverflow.com/a/47673606/313935
for me web config was correct.
if web config is correct then.
check your IIS App pool settings in my case App pool pipeline was selected as the classic I made pipeline integrated and it started working.
Go to iis -> rightclick on your application pool -> advance settings ->
Managed Pipelined Mode -> "integrated" -> ok
I am using Visual Studio 2015 ASP.NET 4.5 Web Forms Web Application project and apparently a bad route in an API Controller will also cause this error. I fixed the route and the error went away.
It certainly would be nice for a more descriptive error message as to why the client framework won't load. I spent hours checking web.config settings, clearing the .net temporary directories, checking global.ascx, etc.. The strange thing is while IE 11 died while loading default.aspx, chrome was able to load default.aspx and the web site.
Try changing on the web.config the compilation to false:
<compilation debug="false" targetFramework="4.5">
If none of these answers work for you then you might be in my situation.
Ok, so for me the issue was caused by the ssl certificate expiring today, so after I renewed it then these errors went away.

Calling webmethod in code behind from client jQuery

I am trying to use jQuery to directly call ASP.NET AJAX page methods. I'm using encosia.com as a reference. My inline javascript is
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
</script>
<div id="Result">Click here for the time.</div>
with my webmethod being
<WebMethod()> _
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
I would use FF and check POST sent, but since where I'm at currently only has IE 7 this is a little hard to do. Other relevent information, ASP.net 2.0. Does anyone know what I'm doing wrong?
Update
web.config - pre-existing still not working
<httpModules>
<remove name="FormsAuthentication" />
<remove name="PassportAuthentication" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpModules>
Since you're using ASP.NET 2.0, you'll need to install the ASP.NET AJAX Extensions, like Joe Enos mentioned. I have a bit more info on the necessary configuration work here: http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/
Additionally, the .d wrapper around the response is an addition that didn't come until ASP.NET 3.5. So, even if you've got everything else working right, your msg.d will be undefined in ASP.NET 2.0. Omit the .d and just make that:
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg);
}
In .NET 2.0, you need to make sure you install the ASP.NET AJAX extensions. In .NET 3.5 and 4.0, the encosia solution works without any modifications.
I don't remember exactly what you need to install, but it might be this.
Have you checked your web.config to allow page methods?
<system.web>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
There is a similar issue here at this post here

Error 500 with custom HttpHandler in ASP.NET website (IIS 7.5, Win7)

I'm trying to get custom HttpHandler working in my sample web application. I've been experiencing a lot of issues, but finally got stuck with error 500. Application pool is being run in Classic ASP.NET 2.0 mode. Server is IIS 7.5, OS is Win 7 Pro.
Here's a code of my handler:
public class SampleHandler : IHttpHandler
{
public SampleHandler()
{
}
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
context.Response.ContentType = "text/html";
context.Response.Write("This is a sample content.");
context.Response.Expires = 0;
context.Response.End();
}
}
Here is a web.config file content:
<?xml version="1.0"?>
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.shc" type="SampleHandler"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add resourceType="Unspecified" verb="*" path="*.shc" name="SampleHandler" type="SampleHandler" modules="IsapiModule" scriptProcessor="c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll\aspnet_isapi.dll"/>
</handlers>
</system.webServer>
</configuration>
Here is a link to the screenshot of an error : http://bit.ly/cmPk4i
Could anybody please tell me what I did wrong? Thanks in advance!
Try setting
<validation validateIntegratedModeConfiguration="false" />
in
<system.webServer>
I had 500 error and this fixed it.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add .... />
</handlers>
</system.webServer>
From the list of "things you can try", did you install the .Net Extensibility Feature?
You can also enable the Failed Requests logging feature on the application, which provides detailed information on request processing.
The good news, at least, is that your registered handler is recognized as the handler to be executed.

Error while accessing ASP.net webservice using JQuery - JSONP

Please look at the code below and help me to figure out what am I doing wrong in my web service code. I want to set up an asp.net web service that can be consumed using an JSONP. I am using Jquery at client side to access the site. Even after setting up proper attributes my web service still emits xml due to which the aynch call fails.
Web Service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json, XmlSerializeString=false, UseHttpGet=true)]
public string HelloWorld(int id, string __callback) {
return __callback + "({message: 'Hello World'})";
}
}
Web Service Response:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">test({message: 'Hello World'})</string>
Web.Config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"
validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule"
type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
Javascript
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:54404/jsonp/webservice.asmx/HelloWorld?id=2&__callback=?", //?jsonp=MatchSvcCallback
dataType: "jsonp",
data: {},
//jsonp : "MatchSvcCallback",
success: function(msg) {
alert("Inside success callback function"); // not being called
},
error: function(xhr, msg){
var response = JSON.parse(xhr.responseText);
}
});
The js code works with an handler, but fails for the webservice due to xml response.
I think the problem here is because jQuery doesn't set the Content-Type header in the HTTP request for HTTP GET's when using $.ajax(). It only gets sent if the request type is 'POST'. This seems to be the case for both dataType: "jsonp" and dataType: "json".
I tried your example and watched the request/response exchange in Fiddler and sure enough I don't see Content-Type: application/xml; charset=UTF-8 being sent in the headers for HTTP GET requests. The header does get sent if using HTTP POST. I'm guessing the presence of this header is a cue for the ASP.NET web service plumbing to decide whether to return either a JSON or XML formatted response.
It seems you're not the only one with this problem, see the following article on the on Elegant Code website:
Calling Remote ASP.NET Web Services from JQuery
The solution appears to be one of the following:
Use a HttpModule to inject the Content-Type: application/xml; charset=UTF-8 header into the request stream as described in the article above.
Use a HttpHandler for the endpoint as you explained you were doing prior to using an ASP.NET web service.
Try Rick Strahl's page based approach
in the following article (which
is in effect a HttpHandler anyway): JSONP for cross-site Callbacks.

Resources