1

我已经阅读了有关此问题的所有帖子,但没有解决问题。如果有人可以帮助我,我会很高兴。

我添加了一个带有 Web 服务的 MVC3 项目。我只有一个名为 Test 的函数,当我通过 HTTP GET 方法(常规 url)调用它时,它以 XML 格式而不是 JSON 返回数据。我怎样才能让它返回 JSON?

网络服务:

namespace TestServer
{
    [WebService]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class TestWebservice : System.Web.Services.WebService
    {  
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        [WebMethod]
        public List<string> Test()
        {    
            return new List<string>
                {
                    {"Test1"},
                    {"Test2"}
                };                    
        }
    }
}

web.config(仅相关部分):

<configuration>
  <location path="TestWebservice.asmx">
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
        </protocols>
      </webServices>
    </system.web>
  </location>  
  <system.web>
    <webServices>
      <protocols>
        <clear/>
      </protocols>
    </webServices>
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx"
        type="System.Web.Script.Services.ScriptHandlerFactory"
        validate="false"/>
    </httpHandlers>
  </system.web>
</configuration>


网址:

http://localhost:49740/testwebservice.asmx/Test


结果(这不是我想要的):

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
  <string>Test1</string>
  <string>Test2</string>
</ArrayOfString>


如果有人可以帮助我,我会很高兴。

4

2 回答 2

3

application/json发送请求时需要指定内容类型 HTTP 标头。例如,如果您使用的是 jQuery AJAX,您可以执行以下操作:

$.ajax({
    url: '/testwebservice.asmx/Test',
    type: 'GET',
    contentType: 'application/json',
    success: function(result) {
        alert(result.d[0]);
    }
});

您还需要在[ScriptMethod]属性上启用 GET 动词:

[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[WebMethod]
public List<string> Test()
{
    return new List<string>
    {
        {"Test1"},
        {"Test2"}
    };
}

您还可以摆脱您在web.config此服务中添加的所有内容。这不是必需的。

哦,顺便说一句,经典的 ASMX Web 服务是一种过时的技术。您应该使用更新的技术,例如返回 JSON、WCF 的 ASP.NET MVC 控制器操作,甚至是最前沿的 ASP.NET MVC 4 Web API。

于 2012-06-27T08:41:12.757 回答
0

REST 服务根据客户端发送的Accept标头以特定格式(XML、JSON)序列化数据。它是Accept向服务说明客户端可以接受的格式的标头。

当您尝试直接从浏览器 URL 访问服务时,Accept标头的值设置为以下默认值(在 firefox 中)

text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

上面的标头明确表示我可以接受 html、xhtml 或 xml。由于application/xml格式已明确指定,但application/jsonREST 服务未以 xml 格式返回数据。(虽然我不明白有什么用ResponseFormat = ResponseFormat.Json)。

因此,如果您想让服务返回 JSON 数据,您必须指定接受标头的相应格式。如果您使用的是 jQuery,您可以使用$.getJSON()将接受标头设置为 as"application/json"或者您甚至可以$.ajax使用dataTypeas json

http://prideparrot.com/blog/archive/2011/9/returning_json_from_wcfwebapi

于 2012-06-27T10:11:42.177 回答