ASMX Web 服务不返回 JSON,只能使用 application/x-www-form-urlencoded contentType 进行 POST

发布于 2024-07-21 18:54:42 字数 1228 浏览 4 评论 0原文

我可以使用 jQuery 调用我的 web 服务,如果 contentType = "application/x-www-form-urlencoded; charset=utf-8"

但是,这将返回 xml: [myjson]

如果我尝试使用“application/json; charset=utf-8”POST 到服务,我会收到带有空 StackTrace 和 ExceptionType 的 500 错误。 我的网络服务功能从未被命中,所以我不太确定如何调试这种情况。

我的方法和类使用适当的属性进行装饰,并设置为使用 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); }
});

我的 web 服务类:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

叹梦 2024-07-28 18:54:42

我在 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");
        }
    });

是我的网络服务的片段:

……

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

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()
        {
如梦初醒的夏天 2024-07-28 18:54:42

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

我发现,如果我将内容类型更改为 application/jsonrequest,它就可以顺利完成,并且我能够在 Web 服务器中处理数据。

只是为了笑,我将上面提到的行添加到我的 web.config 中,但它并没有使 application/json 工作。

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.

尹雨沫 2024-07-28 18:54:42

不确定它是否可以如此简单,但我正在使用 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 调用看起来几乎相同,所以没有问题。

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.

冷情 2024-07-28 18:54:42

如果您在 IE 中进行测试,请尝试从 contentType 属性中删除字符集声明(即它应该如下所示:

contentType: "application/json",

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

替代文字

If you're testing this in IE, try removing the charset declaration from your contentType attribute (i.e. 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.

alt text

浊酒尽余欢 2024-07-28 18:54:42

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

[WebGet(ResponseFormat= WebMessageFormat.Json)]

链接可能会有所帮助。 WebInvoke 有一篇类似的文章(主要用于发布)。

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

贩梦商人 2024-07-28 18:54:42

我经常使用 JQuery AJAX JSON 调用 ASMX Web 服务。 它在所有浏览器中都能完美运行。 我使用的是 .NET 2.0,并安装了 ASP.NET AJAX 扩展(捆绑在 3.5 中)。

我的班级有与您相同的装饰器。 我的方法只有 [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"); }
});

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

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.

自此以后,行同陌路 2024-07-28 18:54:42

看起来您必须在 scriptMethod 标记中指定 json 作为响应格式。 这是来自 vb.net,但我相信您明白了:

ResponseFormat:=ResponseFormat.Json

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文