How to Get JSON Response from a 3.5 Asmx Web Service

How to get JSON response from a 3.5 asmx web service

I faced the same issue, and included the below code to get it work.

[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write("Hello World");
//return "Hello World";
}

Update:

To get a pure json format, you can use javascript serializer like below.

public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HelloWorldData data = new HelloWorldData();
data.Message = "HelloWorld";
Context.Response.Write(js.Serialize(data));

}
}

public class HelloWorldData
{
public String Message;
}

However this works for complex types, but string does not show any difference.

Returning JSON from ASMX, and handling it correctly in Javascript

It seems to me that your main problem that you try to manually use JavaScriptSerializer().Serialize instead of returning an object. The response from the web service will be double JSON encoded.

You are right! There are a lot of a close questions. Look at here Can I return JSON from an .asmx Web Service if the ContentType is not JSON? and Can't get jQuery Ajax to parse JSON webservice result and you will (I hope) find the answer.

UPDATED: Sorry, but you have a small error somewhere what you didn't posted. To close the problem I created a small project with an old version of Visual Studio (VS2008) which has practically exactly your code and which work. I placed it on http://www.ok-soft-gmbh.com/jQuery/WSMember.zip. You can download it, compile and verify that it works. Then you can compare your code with my and find your error.

Best regards

asp.net 3.5 webservice will not return JSON

JSON is not possible with .asmx you need to use WCF web service to return the data in json format.

Read this for HTTP Programming with WCF and the .NET Framework 3.5

Return JSON from ASMX web service, without XML wrapper?

Use this:

var JsonString = ....;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "YourWebServiceName.asmx/yourmethodname",
data: "{'TheData':'" + JsonString + "'}",
dataType: "json",
success: function (msg) {
var data = msg.hasOwnProperty("d") ? msg.d : msg;
OnSucessCallBack(data);
},
error: function (xhr, status, error) {
alert(xhr.statusText);
}
});

function OnSuccessCallData(DataFromServer) {
// your handler for success
}

and then on the server side, in the code behind file that's auto-generated in your AppCode folder, you write something like this:

using System.Web.Services;
using System.Web.Script.Serialization;

[System.Web.Script.Services.ScriptService]
public class YourWebServiceName : System.Web.Services.WebService
{
[WebMethod]
public string yourmethodname(string TheData)
{
JavascriptSerializer YourSerializer = new JavascriptSerializer();
// custom serializer if you need one
YourSerializer.RegisterConverters(new JavascriptConverter [] { new YourCustomConverter() });

//deserialization
TheData.Deserialize(TheData);

//serialization
TheData.Serialize(TheData);
}
}

If you don't use a custom converter, the properties between the json string and the c# class definition of your server-side object must match for the deserialization to work. For the serialization, if you don't have a custom converter, the json string will include every property of your c# class. You can add [ScriptIgnore] just before a property definition in your c# class and that property will be ignored by the serializer if you don't specify a custom converter.

How to return JSON from a 2.0 asmx web service

It's no problem to return JSON from ASMX services in ASP.NET 2.0. You just need the ASP.NET AJAX Extensions installed.

Do be sure to add the [ScriptService] decoration to your web service. That's what instructs the server side portion of the ASP.NET AJAX framework to return JSON for a properly formed request.

Also, you'll need to drop the ".d" from "msg.d" in my example, if you're using it with 2.0. The ".d" is a security feature that came with 3.5.

asp.net asmx web service returning xml instead of json

Finally figured it out.

The app code is correct as posted. The problem is with the configuration. The correct web.config is:

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<handlers>
<add name="ScriptHandlerFactory"
verb="*" path="*.asmx"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
resourceType="Unspecified" />
</handlers>
</system.webServer>
</configuration>

According to the docs, registering the handler should be unnecessary from .NET 4 upwards as it has been moved to the machine.config. For whatever reason, this isn't working for me. But adding the registration to the web.config for my app resolved the problem.

A lot of the articles on this problem instruct to add the handler to the <system.web> section. This does NOT work and causes a whole load of other problems. I tried adding the handler to both sections and this generates a set of other migration errors which completely misdirected my troubleshooting.

In case it helps anyone else, if I had ther same problem again, here is the checklist I would review:

  1. Did you specify type: "POST" in the ajax request?
  2. Did you specify contentType: "application/json; charset=utf-8" in the ajax request?
  3. Did you specify dataType: "json"in the ajax request?
  4. Does your .asmx web service include the [ScriptService] attribute?
  5. Does your web method include the [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    attribute? (My code works even without this attribute, but a lot of articles say that it is required)
  6. Have you added the ScriptHandlerFactory to the web.config file in <system.webServer><handlers>?
  7. Have you removed all handlers from the the web.config file in in <system.web><httpHandlers>?

Hope this helps anyone with the same problem. and thanks to posters for suggestions.



Related Topics



Leave a reply



Submit