views:

4451

answers:

7

I can call my webservice using jQuery IF the contentType = "application/x-www-form-urlencoded; charset=utf-8"

This will, however, return the xml: <string>[myjson]</string>

If I try to POST to the service using "application/json; charset=utf-8" I receive a 500 error with an empty StackTrace and ExceptionType. My webservice function is never hit so I'm not quite sure how to debug this situation.

My methods and classes are decorated with the appropriate attributes and are set to use JSON as their response type (as do my wsdl and disco files). I have the Ajax extensions installed and the required entries in web.config.

This is on a SharePoint farm, but I'm not sure that makes too much of a difference. I deployed the web.config changes on all WFE's as well as installed the ajax extensions. Again the service works, it just will not accept anything but the default content type.

Not sure what I'm missing here, fellas...

my ajax call:

$.ajax({
type: "POST",
url: "/_vti_bin/calendar.asmx/Test",
dataType: "json",
data: "{}",
contentType: "application/json; charset=UTF-8",
success: function(msg){
    alert(msg);
    },
error: function(xhr, msg){ alert(msg + '\n' + xhr.responseText); }
});

My webservice class:

[WebService(Namespace = "http://namespace")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]
public class CalendarService : WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string Test()
    {
        return "Hello World";
    }
}
A: 

not sure if it could be this simple but I am using jQuery to call back JSON from my web methods.

the main difference I see is the attribute of the class

[System.Web.Script.Services.ScriptService]

    [WebService(Namespace = "http://MyNameSpace")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class Web : System.Web.Services.WebService{

       [WebMethod]
       public string TestMethod(){
         return "Testing";
       }

    }

I have to assume you are using the 3.5 framework because that is the only way to expose JSON web methods.

My calls form jQuery look virtually identical, so no issue there.

Bobby Borszich
tried this and still am getting the XML wrapper...
Steve Ruiz
A: 

Looks like you have to specify json as the response format in the scriptMethod tag. This is from vb.net, but I'm sure you get the idea:

ResponseFormat:=ResponseFormat.Json

ScottE
as you can see in the pasted code, I am supplying the response format to the ScriptMethod attribute.
Steve Ruiz
A: 
Phil.Wheeler
+1  A: 

I think you're looking for the WebInvoke or WebGet Attribute, it lets you specify Uri Template, body style, request and responseformats, for example:

[WebGet(ResponseFormat= WebMessageFormat.Json)]

This Link may help. There's a similar article for WebInvoke (used mostly for post).

marr75
The question was about ASMX web service; WebGet applies to WCF contracts.
Alek Davis
A: 

I use JQuery AJAX JSON calls to ASMX webservice quite a bit. It works perfectly in all browsers. I'm using .NET 2.0 with the ASP.NET AJAX Extensions installed (bundled in 3.5).

My class has the same decorators as your. My methods only have the [WebMethod(EnableSession = true)] decorator. My web.config however has the following entry in its httpHandlers section:

<add verb="*" path="*jsonservice.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

My jquery call looks as follows:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "path/to/service/jsonservice.asmx/MethodName",
    data: JSON.stringify(DTO),
    dataType: "json",
    success: function(rtrn) { alert("good"); },
    error: function(req, msg, err) { alert("bad"); }
});

This article is the root of my knowledge.

Mr Grieves
+2  A: 

I have this working in 2.0 using web services, but I have put in place protection from the .d (see dataFilter below). I also am returning an array of objects. NOTE: the class for the object is static, or it would not work correctly for me at least.

  $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "webservice/ModifierCodesService.asmx/GetModifierList",
        success: function(msg)
        {
            LoadModifiers(msg);
        },
        failure: function(msg)
        {
            $("#Result").text("Modifiers did not load");
        }
    });

Here is a snippett of my web service:

...

[WebService(Namespace = "http://mynamespace.com/ModifierCodesService/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class ModifierCodesService : System.Web.Services.WebService
{

     /// <summary>
    /// Get a list of Modifiers
    /// </summary>
    /// <returns></returns>
    [WebMethod(EnableSession = true)]
    public Modifier[] GetModifierList()
    {
        return GetModifiers();
    }
       /// <summary>
        /// Modifiers list from database
        /// </summary>
        /// <returns></returns>
        private Modifier[] GetModifiers()
        {
            List<Modifier> modifier = new List<Modifier>();
            ModifierCollection matchingModifiers = ModifierList.GetModifierList();
            foreach (Modifier ModifierRow in matchingModifiers)
            {
                modifier.Add(new Modifier(ModifierRow.ModifierCode, ModifierRow.Description));
            }
            return modifier.ToArray();
        }
    }

...

the object code:

 public static class ModifierList
    {

        /// <summary>
        /// Returns the Modifier Collection.
        /// </summary>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public static ModifierCollection GetModifierList()
        {
Mark Schultheiss
SO bottom line changepublic string Test() {to public static string Test() {and see if that works for you.
Mark Schultheiss
+1  A: 

I have been fighting with this today with an iPhone app talking to a .Net Web Service.

I found that if I changed my Content Type to application/jsonrequest it went through without a problem and I was able to process the data in my web server.

Just for grins I added the line mentioned above to my web.config, but it did not make application/json work.

Steve Reed Sr