简体   繁体   中英

ASMX webservice not returning JSON, can only POST using application/x-www-form-urlencoded contentType

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";
    }
}

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()
        {

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.

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.

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.

If you're testing this in IE, try removing the charset declaration from your contentType attribute (ie it should look like this:

contentType: "application/json",

I have yet to discover why, but IE seems to get its knickers in a twist when making JSON calls with the " charset=UTF-8 " part.

替代文字

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM