Goran
Goran

Reputation: 19

Webservice ignores ResponseFormat.Json

I want to do a simple $.ajax POST to my asp.net Webservice, returning Json. I've tried all the possible solutions out there, without any luck. Am I missing something?

My jQuery code:

$.ajax({
    type: "POST",
    url: "/Services/ConfiguratorService.asmx/GetInitialJson",
    contentType: "application/json; charset=utf-8",
    data: "{}",
    dataType: "json",
    success: function (data, textStatus, jqXhr) {
        if (data != null) {
            alert(data.d);
        } else {
            alert("data undefined: | " + jqXhr + " | " + textStatus);
        }
    },
    error: function (jqXhr, textStatus, errorThrown) {
        alert(jqXhr + " | " + textStatus + " | " + errorThrown);
    }
});

My asmx.cs code:

[WebMethod(Description = "Gets initial configuration values for Configurator")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public ConfiguratorModel GetInitialModel()
{
    return new Item { Title: "10 units", Text: "Item text..." };
}
public class Item { public string Title {get; set;} public string Text {get; set;} }

Update 1: In my solution, I'm getting back a response, but only as XML. I've tried to reproduce the error in a fresh solution, with no luck. Everything works just fine. .asmx services in both old and new solution actually return the same response. The only difference is that jquery in one of them fails with error: parsererror, unexpected token <

Update 2: Response header in my old solution is always "text/xml; charset=utf-8".

Update 3: My web.config has all the entries that are required. Response is still "text/xml; charset=utf-8". Why?

Upvotes: 1

Views: 2537

Answers (4)

Dmitry Shashurov
Dmitry Shashurov

Reputation: 1704

Looks like a bug with ignoring ResponseFormat.Json, found only such a solution:

File "Data.asmx"

<%@ WebService Language="C#" CodeBehind="Data.asmx.cs" Class="WebServiceData" %>

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

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebServiceData : WebService
{
    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void Get()
    {
        string ret = @"{
            ""arg"": {
                ""ReportID"": 1
            }
        }";

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.AddHeader("content-length", ret.Length.ToString());
        HttpContext.Current.Response.Write(ret);
        HttpContext.Current.Response.Flush();
    }
}

Upvotes: 0

Goran
Goran

Reputation: 19

A colleague of mine helped me out, pointing in direction. I found out that handlers were asp.net 2.0. The solution was upgraded from 2.0 to 4.0 earlier this year. all I had to do was replace:

<add name="WebServiceHandlerFactory-Integrated" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="System.Web.Services.Protocols.WebServiceHadlerFactory, System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode" responseBufferLimit="4194304" />

with:

<add name="WebServiceHandlerFactory-Integrated-4.0" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="integratedMode,runtimeVersionv4.0" />

Good idea is to try removing all of the handlers temporarily, adding only:

<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"/>

Upvotes: 1

Viktor S.
Viktor S.

Reputation: 12815

I have such web service:

[WebService(Namespace = "http://example.com/")]
[System.Web.Script.Services.ScriptService]
public class api : System.Web.Services.WebService {
    [WebMethod(EnableSession = true)]
    public ServiceResponse<string> SignIn(string _email, string _password) {...}
}

and $.ajax call like yours. Everything works fine to me. Possibly you need to add [System.Web.Script.Services.ScriptService] to you service class. As far as I remember, that is a key to JSON response. jQuery call is like this:

$.ajax({
      type: "POST",
      url: "/api.asmx/SignIn",
      dataType: "json",
      data: JSON.stringify({"_password": pwd,
                            "_email": email
                        }),
      contentType: 'application/json; charset=utf-8',
      success: function (res) { }
   });

Edit:

public ConfiguratorModel GetInitialModel()
{
    return new Item { Title: "10 units", Text: "Item text..." };
}

This method definition looks wrong. I do not see how you may return Item when return type is ConfiguratorModel. This must fail on compilation.

Upvotes: 0

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

use static keyword to call method as you have do define static method

public static ConfiguratorModel GetInitialModel()
{
    return new Item { Title: "10 units", Text: "Item text..." };
}

Upvotes: 0

Related Questions