C# ASMX 网络服务不返回 JSON,只能使用 application/x-www-form-urlencoded contentType POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/900231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 22:09:57  来源:igfitidea点击:

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

c#jqueryweb-servicessharepointasmx

提问by Steve Ruiz

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

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

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

但是,这将返回 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.

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

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.

我的方法和类使用适当的属性进行修饰,并设置为使用 JSON 作为它们的响应类型(就像我的 wsdl 和 disco 文件一样)。我已经安装了 Ajax 扩展,并且在 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.

这是在 SharePoint 场上,但我不确定这会产生太大的不同。我在所有 WFE 上部署了 web.config 更改并安装了 ajax 扩展。该服务再次起作用,它只接受默认内容类型之外的任何内容。

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

不知道我在这里错过了什么,伙计们......

my ajax call:

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

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

回答by Bobby Borszich

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

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

the main difference I see is the attribute of the class

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

[System.Web.Script.Services.ScriptService]

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

我必须假设您使用的是 3.5 框架,因为这是公开 JSON Web 方法的唯一方法。

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

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

回答by ScottE

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:

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

ResponseFormat:=ResponseFormat.Json

ResponseFormat:=ResponseFormat.Json

回答by Phil.Wheeler

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

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

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.

我还没有发现原因,但 IE 似乎在使用 " charset=UTF-8" 部分进行 JSON 调用时将其内裤弄得一团糟。

alt text

替代文字

回答by marr75

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

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

[WebGet(ResponseFormat= WebMessageFormat.Json)]

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

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

回答by srmark

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

我经常使用 JQuery AJAX JSON 调用 ASMX 网络服务。它在所有浏览器中都能完美运行。我使用 .NET 2.0 并安装了 ASP.NET AJAX 扩展(捆绑在 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:

我的班级和你的班级有相同的装饰者。我的方法只有[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" />

My jquery call looks as follows:

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

This articleis the root of my knowledge.

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

回答by Mark Schultheiss

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.

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

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

回答by Steve Reed Sr

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

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

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.

我发现,如果我将内容类型更改为 application/jsonrequest,它会顺利通过,并且我能够在我的 Web 服务器中处理数据。

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

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