Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Web Service won't output JSON, only XML

I'm trying to use jQuery and JSON with a C# Web Service that I wrote. No matter what, the following code will only output in XML.

Webservice Code

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
    return "Hello World!";
}

I also have these attributes assigned to the class

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]

jQuery Code

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "ScheduleComputerDS.asmx/HelloWorld",
    data: "{}",
    dataType: "jsonp",
    success: function(data) {
        alert(data);
    }
});

The ASMX page always returns as content type "text/xml". Anything I'm missing?

EDITS: In response to a couple answers:

If I have the datatype as just "json" the content is still XML and jQuery also will not call my callback function. If I add the "&callback=?" to the url, IIS throws a HTTP 500 error.

My class does inherit from "System.Web.Services.WebService".

From doing some research on your guys answers, it looks like I do need to mess with WCF. Unfortunately the JSON that is returned is more designed for MS Ajax and is a lot of useless bloat for my use. I may look into an open source library like Jayrock or something similar.

Thanks for all your help!

like image 614
TheDude Avatar asked Mar 19 '09 19:03

TheDude


2 Answers

I think there's a typo:

dataType: "jsonp",

Should be:

dataType: "json",
like image 136
eduncan911 Avatar answered Sep 20 '22 15:09

eduncan911


As far as I know, the ScriptService attribute just allows the service to automatically create a JavaScript proxy (by appending /js to the endpoint address - ScheduleComputerDS.asmx/js in your case). It does not allow you to call the operations on the service the way you're trying to do.

You could instead use a RESTful WCF service (which requires .NET 3.5) which you can access by sending a properly shaped URI via an HTTP GET.

like image 31
Rob Windsor Avatar answered Sep 22 '22 15:09

Rob Windsor