ASMX web服务没有返回JSON,只能使用application/x-www-form-urlencoded contentType进行POST请求。

8
如果contentType="application/x-www-form-urlencoded; charset=utf-8",我可以使用jQuery调用我的webservice。然而,这将返回xml:<string>[myjson]</string>如果我尝试使用"application/json; charset=utf-8"进行POST,则会收到500错误,StackTrace和ExceptionType为空。我的webservice函数未被调用,因此我不知道如何调试此情况。我的方法和类都装饰有适当的属性,并设置为使用JSON作为其响应类型(我的wsdl和disco文件也是如此)。我安装了Ajax扩展并在web.config中添加了必需的条目。这是在SharePoint农场上,但我不确定这是否会产生太大的影响。我在所有WFE上部署了web.config更改,并安装了ajax扩展程序。再次强调该服务起作用,只是除了默认内容类型之外无法接受任何东西。不确定我错过了什么,伙计们...我的ajax调用:
$.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); }
});

我的 WebService 类:

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

当执行 AJAX 请求时,ASP.NET MVC 1.0 也会发生同样的情况。 - Eugeniu Torica
7个回答

3

我在2.0版本中使用web服务使其正常运作,但我已经设置了保护措施以防止.d文件(请参见下面的dataFilter)。我还返回了一个对象数组。注意:对象的类是静态的,否则它至少对我来说无法正常工作。

  $.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");
        }
    });

以下是我的Web服务代码片段:

...

[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();
        }
    }

目标代码:
 public static class ModifierList
    {

        /// <summary>
        /// Returns the Modifier Collection.
        /// </summary>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public static ModifierCollection GetModifierList()
        {

1
将以下代码中的“public string Test()”改为“public static string Test()”,然后看看是否能解决您的问题。 - Mark Schultheiss

1

今天我一直在解决一个问题,就是 iPhone 应用程序与 .Net Web 服务通信的问题。

我发现,如果将 Content Type 更改为 application/jsonrequest,就可以顺利地进行通信,并且我能够在 Web 服务器上处理数据。

只是为了好玩,我将上面提到的那行代码添加到了我的 web.config 文件中,但它并没有使 application/json 起作用。


0

不确定是否可以这么简单,但我正在使用jQuery从我的Web方法中回调JSON。

我看到的主要区别是类的属性。

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

    }

我得假设你正在使用3.5框架,因为这是唯一公开JSON Web方法的方式。

我的jQuery调用看起来几乎相同,所以没有问题。


0
如果您正在IE中测试此内容,请尝试从contentType属性中删除charset声明(即它应该像这样:)。
contentType: "application/json",

我还没有发现为什么,但是当使用“charset=UTF-8”部分进行JSON调用时,IE似乎会出现问题。

alt text


0

我认为你正在寻找WebInvoke或WebGet属性,它可以让你指定Uri模板、正文样式、请求和响应格式,例如:

[WebGet(ResponseFormat= WebMessageFormat.Json)]

这个链接 可能会有所帮助。还有一篇类似的文章介绍了WebInvoke(主要用于POST请求)。


1
问题是关于 ASMX Web 服务的;WebGet 适用于 WCF 合同。 - Alek Davis

0

我经常使用JQuery AJAX JSON调用ASMX webservice。在所有浏览器中都可以完美运行。我正在使用安装了ASP.NET AJAX扩展(捆绑在3.5中)的.NET 2.0。

我的类与你的类具有相同的修饰符。我的方法只有[WebMethod(EnableSession = true)]修饰符。然而,我的web.config文件在其httpHandlers部分具有以下条目:

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

我的 jQuery 调用如下:

$.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"); }
});

这篇文章是我知识的根源。


-1

看起来你需要在scriptMethod标签中指定json作为响应格式。这是来自vb.net的,但我相信你明白这个想法:

ResponseFormat:=ResponseFormat.Json


正如您在粘贴的代码中所看到的,我正在向ScriptMethod属性提供响应格式。 - Steve Ruiz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接