Asmx Web Service How to Return JSON and Not Xml

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.

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.

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.

When I Make my (ASMX) web service accept/return JSON instead of XML, is it no longer considered SOAP?

You define what kind of requests are made to you web service (asmx). Many protocols are allowed:
HTTP POST,
HTTP GET,
SOAP 1.1,
SOAP 1.2,
etc... OR you can block any of them.

When you call the web service with javascript you can use POST or GET. It doesn't matter. The trick is what type of content you tell the service to return in these calls. You can tell the service to send you JSON or you can tell the service to send you XML.

When you create a service client in Visual Studio to connect to a ASMX service, Visual studio will try to access the WSDL for the service and the client will be in charge of generating the SOAP envelopes to communicate with the service and in this case you will send and receive XML because thats what the client and server have agreed to use to communicate.

How to let an ASMX file output JSON

From WebService returns XML even when ResponseFormat set to JSON:

Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.

Though it's written specifically for jQuery, this may also be useful to you:

Using jQuery to Consume ASP.NET JSON Web Services

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.



Related Topics



Leave a reply



Submit