C# 如何从 3.5 asmx Web 服务获取 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19563641/
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-10 15:18:19  来源:igfitidea点击:

How to get JSON response from a 3.5 asmx web service

c#asp.netjsonasmxjavascriptserializer

提问by Mansinh

I have the following method:

我有以下方法:

using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Collections;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]

// [System.Web.Script.Services.ScriptService]
public class Tripadvisor : System.Web.Services.WebService {

    public Tripadvisor () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }


    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HotelAvailability(string api)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string json = js.Serialize(api);
        //JsonConvert.SerializeObject(api);
        return json ;
    }

Here i set ResponseFormat attribute is json s still being returned as XML.

在这里,我将 ResponseFormat 属性设置为 json 仍然作为 XML 返回。

I want to json format using this asmx service Any ideas?

我想使用这个 asmx 服务进行 json 格式有什么想法吗?

采纳答案by Saranya

I faced the same issue, and included the below code to get it work.

我遇到了同样的问题,并包含以下代码以使其正常工作。

[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write("Hello World");
    //return "Hello World";
}

Update:

更新:

To get a pure json format, you can use javascript serializer like below.

要获得纯 json 格式,您可以使用如下所示的 javascript 序列化程序。

public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
    public void HelloWorld()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";           
        HelloWorldData data = new HelloWorldData();
        data.Message = "HelloWorld";
        Context.Response.Write(js.Serialize(data));


    }
}

public class HelloWorldData
{
   public String Message;
}

However this works for complex types, but string does not show any difference.

然而,这适用于复杂类型,但 string 没有显示任何区别。

回答by aravind

Just a doubt. When are you not getting a JSON response? Because when you invoke the web service from the client (I am assuming a web browser, i.e. xhr), you should specify the content type header on the request as "application/json; charset=yourcharset".

只是一个疑问。你什么时候没有收到 JSON 响应?因为当您从客户端调用 Web 服务时(我假设是一个 Web 浏览器,即 xhr),您应该将请求中的内容类型标头指定为“application/json; charset=yourcharset”。

I believe the above solution always returns json, no matter what the content type is specified from the client. The dotnet asmx framework allows this using the content-type header method, so the above could be classified as a hack, when a neat solution is available.

我相信上述解决方案总是返回 json,无论客户端指定的内容类型是什么。dotnet asmx 框架允许使用内容类型标头方法进行此操作,因此当有简洁的解决方案可用时,上述内容可以归类为黑客攻击。

Similar question at Return Json Data from ASMX web service

从 ASMX Web 服务返回 Json 数据的类似问题

This might help too -> http://forums.asp.net/p/1054378/2338982.aspx#2338982

这也可能有帮助-> http://forums.asp.net/p/1054378/2338982.aspx#2338982

P.S: I am assuming you are using dotnet version 4.

PS:我假设您使用的是 dotnet 版本 4。

回答by Stephen Kennedy

Dear future readers: The currently accepted answer is not the right way. It ties you to using the JavaScriptSerializerand you lose the ability to request xml (or indeed any serialization format which may come along in the future). The "right way" also involves less code!

亲爱的未来读者:目前接受的答案不是正确的方法。它将您与使用联系起来,JavaScriptSerializer并且您将失去请求 xml(或将来可能出现的任何序列化格式)的能力。“正确的方式”还涉及更少的代码!

If you decorate your service class with the [ScriptService]attribute - which you have - then ASP.NET 3.5+ should automatically serialise the response to JSONprovided your Ajax call requests JSON. The suggestions to serialise to JSON manually are simply wrong, unless you wish to use a different serialiser such as Newtonsoft.

如果你用你拥有的[ScriptService]属性装饰你的服务类,那么ASP.NET 3.5+ 应该自动将响应序列化为 JSON提供你的Ajax 调用请求 JSON。手动序列化为 JSON 的建议是完全错误的,除非您希望使用不同的序列化程序,例如 Newtonsoft。

That you were seeing XML suggests one of the following:

您看到的 XML 表明以下情况之一:

  • You are not requesting JSON in your Ajax call - please see working example code below
  • Possibly some web.config entries are missing, according to an answer here(disclaimer: I don't have most of these in a production web.config; only start playing with these if nothing else works)
  • 您没有在 Ajax 调用中请求 JSON - 请参阅下面的工作示例代码
  • 根据这里的答案,可能缺少一些 web.config 条目(免责声明:我在生产 web.config 中没有这些条目;只有在没有其他工作的情况下才开始使用这些条目 )

Here is a simple working example of a JSON enabled ASMX web service:

这是启用 JSON 的 ASMX Web 服务的简单工作示例:

<%@ WebService Language="C#" Class="WebService" %>
using System;
using System.Collections.Generic;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    [WebMethod]
    public MyClass Example()
    {
        return new MyClass();
    }

    public class MyClass
    {
        public string Message { get { return "Hi"; } }
        public int Number { get { return 123; } }
        public List<string> List { get { return new List<string> { "Item1", "Item2", "Item3" }; } }
    }
}

JavaScript to request it and process the response (we'll simply pop up a JS alert with the message from MyClass.Message) :

JavaScript 来请求它并处理响应(我们将简单地弹出一个带有来自 MyClass.Message 的消息的 JS 警报):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.js" type="text/javascript"></script>  
</head>
<body>
    <script type="text/javascript">
        $.ajax({
            type: "POST",
            url: "WebService.asmx/Example",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{ }",
            error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); },
            success: function (msg) {
                alert(msg.d.Message);
            }
        });
    </script>
</body>
</html>

Http request:

Http请求:

POST http://HOST.com/WebService.asmx/Example HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://HOST.com/Test.aspx
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 3
Host: HOST.com

{ }

HTTP response:

HTTP响应:

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 20 Feb 2018 08:36:12 GMT
Content-Length: 98

{"d":{"__type":"WebService+MyClass","Message":"Hi","Number":123,"List":["Item1","Item2","Item3"]}}

Result:

结果:

"Hi" is displayed in a JS popup.

“嗨”显示在 JS 弹出窗口中。