【问题标题】:asp.net asmx web service returning xml instead of jsonasp.net asmx Web 服务返回 xml 而不是 json
【发布时间】:2012-06-20 17:51:47
【问题描述】:

为什么这个简单的 Web 服务拒绝向客户端返回 JSON?

这是我的客户端代码:

        var params = { };
        $.ajax({
            url: "/Services/SessionServices.asmx/HelloWorld",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            timeout: 10000,
            data: JSON.stringify(params),
            success: function (response) {
                console.log(response);
            }
        });

还有服务:

namespace myproject.frontend.Services
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class SessionServices : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

web.config:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

然后回应:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

无论我做什么,响应总是以 XML 形式返回。如何让网络服务返回 Json?

编辑:

这是 Fiddler HTTP 跟踪:

REQUEST
-------
POST http://myproject.local/Services/SessionServices.asmx/HelloWorld HTTP/1.1
Host: myproject.local
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://myproject.local/Pages/Test.aspx
Content-Length: 2
Cookie: ASP.NET_SessionId=5tvpx1ph1uiie2o1c5wzx0bz
Pragma: no-cache
Cache-Control: no-cache

{}

RESPONSE
-------
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 19 Jun 2012 16:33:40 GMT
Content-Length: 96

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

我已经不知道我现在阅读了多少篇文章试图解决这个问题。这些说明要么不完整,要么由于某种原因无法解决我的问题。 一些更相关的包括(都没有成功):

加上其他几篇一般性文章。

【问题讨论】:

  • 我看到目标框架标签设置为4.0,您的应用实际内置的框架版本是什么?
  • 在应用程序选项卡上的项目属性下,目标框架是“.Net Framework 4”。这是否足够,还是我需要将其设置在其他地方?抱歉,我对 VS 比较陌生(更多 js 经验)
  • 您的代码看起来正确。请您使用 WireShark 记录您的 AJAX 请求和服务器的回复好吗?查看这些 HTTP 数据包有助于了解发生了什么。
  • @kol:感谢您花时间看这个。我已按要求发布了 HTTP 跟踪。也许你能看到我遗漏的东西。

标签: c# asp.net json web-services asmx


【解决方案1】:

终于明白了。

发布的应用代码正确无误。问题出在配置上。正确的 web.config 是:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.webServer>
        <handlers>
            <add name="ScriptHandlerFactory"
                 verb="*" path="*.asmx"
                 type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                 resourceType="Unspecified" />
        </handlers>
    </system.webServer>
</configuration>

根据文档,从 .NET 4 向上注册处理程序应该是不必要的,因为它已被移动到 machine.config。无论出于何种原因,这对我不起作用。但是将注册添加到我的应用程序的 web.config 解决了问题。

很多关于这个问题的文章都指示将处理程序添加到&lt;system.web&gt; 部分。这不起作用,并导致一大堆其他问题。我尝试将处理程序添加到这两个部分,这会产生一组其他迁移错误,这完全误导了我的故障排除。

如果它对其他人有帮助,如果我再次遇到同样的问题,这是我要查看的清单:

  1. 您是否在 ajax 请求中指定了type: "POST"
  2. 您是否在 ajax 请求中指定了contentType: "application/json; charset=utf-8"
  3. 您是否在 ajax 请求中指定了dataType: "json"
  4. 您的 .asmx Web 服务是否包含 [ScriptService] 属性?
  5. 您的网络方法是否包含[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 属性? (我的代码即使没有这个属性也可以工作,但是很多文章都说它是必需的)
  6. 您是否已将ScriptHandlerFactory 添加到&lt;system.webServer&gt;&lt;handlers&gt; 中的web.config 文件中?
  7. 您是否从&lt;system.web&gt;&lt;httpHandlers&gt; 中的 web.config 文件中删除了所有处理程序?

希望这对遇到同样问题的人有所帮助。并感谢海报的建议。

【讨论】:

  • 我已经为此苦苦挣扎了好几个小时,您的帖子非常有帮助。我已经完成了所有七个步骤,我的服务仍在响应中返回 xml。我正在使用 ASP.NET 3.5 - 还有其他想法吗?我也在使用 jQuery 表单插件(不需要显式声明 POST、json 等)
  • 如果您打开一个新问题并在此处添加评论链接到它,我可以看看。请包括请求和响应的提琴手跟踪。包括您的完整 web.config。并且还包括专门包含属性的asp.net 代码。我建议您按照我的示例使用类似的“Hello World”服务进行测试。
  • 这个答案对我帮助很大,尤其是他提到的七个步骤。
  • 我在我的应用程序中使用了同样的方法,但是我遇到了一个错误,你能告诉我我在这里缺少什么吗? XMLHttpRequest 无法加载 192.168.200.56/ChatApp.asmx/HelloWorld。无效的 HTTP 状态代码 500
  • 为 #2 添加更多魔法,将 contentType 更改为 "application/json" 解决了我的问题。
【解决方案2】:

上述解决方案没有成功,我是如何解决的。

将此行放入您的网络服务中,而不是返回类型,只需在响应上下文中写入字符串

this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serial.Serialize(city));

【讨论】:

  • 你做到了!这是最好的答案。我将我的函数设为“void”返回类型并使用了您的代码,并且 JQuery UI 自动完成功能终于开始工作了。
  • 这既粗鲁又令人担忧,但当更复杂的胡闹似乎无法解决我的问题时,它却非常有效。这行得通。
  • 快乐的兔子! :D
  • 老兄,你是我最好的救星!在看到您的回答之前,我一直在用头撞墙好几个小时,没有其他任何帮助。我只是非常爱你:)
【解决方案3】:

如果您想继续使用 Framework 3.5,您需要对代码进行如下更改。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[ScriptService]
public class WebService : System.Web.Services.WebService
{
    public WebService()
    {
    }

    [WebMethod]
    public void HelloWorld() // It's IMP to keep return type void.
    {
        string strResult = "Hello World";
        object objResultD = new { d = strResult }; // To make result similarly like ASP.Net Web Service in JSON form. You can skip if it's not needed in this form.

        System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
        string strResponse = ser.Serialize(objResultD);

        string strCallback = Context.Request.QueryString["callback"]; // Get callback method name. e.g. jQuery17019982320107502116_1378635607531
        strResponse = strCallback + "(" + strResponse + ")"; // e.g. jQuery17019982320107502116_1378635607531(....)

        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.AddHeader("content-length", strResponse.Length.ToString());
        Context.Response.Flush();

        Context.Response.Write(strResponse);
    }
}

【讨论】:

  • 如果您在答案中添加您使用过的内容并可能链接到文档,将会很有帮助。这样一来,其他人就更容易弄清楚这到底是如何工作的,以及他们如何在其他情况下使用它。
  • 此答案适用于 Sharepoint 2010 和 .NET Framework 3.5 中的 ASMX + jQuery。我决定使用标准 JavaScriptSerializer 而不是参考 NewtonJson 程序集。谢谢!
【解决方案4】:

有更简单的方法可以从 Web 服务返回纯字符串。我称它为 CROW 函数(便于记忆)。

  [WebMethod]
  public void Test()
    {
        Context.Response.Output.Write("and that's how it's done");    
    }

如您所见,返回类型为“void”,但 CROW 函数仍会返回您想要的值。

【讨论】:

  • 这对我来说非常有效。我将字符串返回更改为 void 并使用 context.response.output.write 吐出已序列化的 JSON!
【解决方案5】:

我有一个 .asmx Web 服务 (.NET 4.0),它带有一个返回字符串的方法。该字符串是一个序列化列表,就像您在许多示例中看​​到的那样。这将返回未包装在 XML 中的 json。无需更改 web.config 或需要 3rd 方 DLL。

var tmsd = new List<TmsData>();
foreach (DataRow dr in dt.Rows)
{

m_firstname = dr["FirstName"].ToString();
m_lastname = dr["LastName"].ToString();

tmsd.Add(new TmsData() { FirstName = m_firstname, LastName = m_lastname} );

}

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string m_json = serializer.Serialize(tmsd);

return m_json;

使用该服务的客户端部分如下所示:

   $.ajax({
       type: 'POST',
       contentType: "application/json; charset=utf-8",
       dataType: 'json',
       url: 'http://localhost:54253/TmsWebService.asmx/GetTombstoneDataJson',
       data: "{'ObjectNumber':'105.1996'}",
       success: function (data) {
           alert(data.d);
       },
       error: function (a) {
           alert(a.responseText);
       }
   });

【讨论】:

    【解决方案6】:

    希望这会有所帮助,看来您仍然需要在请求中发送一些 JSON 对象,即使您调用的方法没有参数。

    var params = {};
    return $http({
            method: 'POST',
            async: false,
            url: 'service.asmx/ParameterlessMethod',
            data: JSON.stringify(params),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
    
        }).then(function (response) {
            var robj = JSON.parse(response.data.d);
            return robj;
        });
    

    【讨论】:

      【解决方案7】:

      对我来说,它适用于我从这篇文章中获得的这段代码:

      How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string, wrapped in quotes?

      [WebInvoke(UriTemplate = "HelloWorld", Method = "GET"), OperationContract]
      public Message HelloWorld()
      {
          string jsonResponse = //Get JSON string here
          return WebOperationContext.Current.CreateTextResponse(jsonResponse, "application/json; charset=utf-8", Encoding.UTF8);
      }
      

      【讨论】:

      • ScriptService 属性应该自动处理这个问题。我真的不想自己处理所有序列化的东西。我有其他项目,这些代码工作得很好。但是它们在其他服务器上,这让我觉得存在某种配置问题。
      【解决方案8】:

      我已经尝试了以上所有步骤(甚至是答案),但我没有成功,我的系统配置是 Windows Server 2012 R2,IIS 8。以下步骤解决了我的问题。

      更改了已管理管道 = 经典的应用程序池。

      【讨论】:

        【解决方案9】:

        我知道这确实是个老问题,但我今天遇到了同样的问题,我一直在到处寻找答案,但没有结果。经过长时间的研究,我找到了完成这项工作的方法。要从服务中返回 JSON,您已在请求中以正确的格式提供数据,请在请求之前使用 JSON.stringify() 解析数据,不要忘记 contentType: "application/json; charset=utf-8",使用它应该会提供预期的结果。

        【讨论】:

          【解决方案10】:
          response = await client.GetAsync(RequestUrl, HttpCompletionOption.ResponseContentRead);
          if (response.IsSuccessStatusCode)
          {
              _data = await response.Content.ReadAsStringAsync();
              try
              {
                  XmlDocument _doc = new XmlDocument();
                  _doc.LoadXml(_data);
                  return Request.CreateResponse(HttpStatusCode.OK, JObject.Parse(_doc.InnerText));
              }
              catch (Exception jex)
              {
                  return Request.CreateResponse(HttpStatusCode.BadRequest, jex.Message);
              }
          }
          else
              return Task.FromResult<HttpResponseMessage>(Request.CreateResponse(HttpStatusCode.NotFound)).Result;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-06-02
            • 2012-02-26
            • 2023-04-05
            • 2011-02-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多