asp.net asmx Web 服务返回 xml 而不是 json [英] asp.net asmx web service returning xml instead of json

查看:29
本文介绍了asp.net asmx Web 服务返回 xml 而不是 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的客户端代码:

 var params = { };$.ajax({url: "/Services/SessionServices.asmx/HelloWorld",类型:POST",contentType: "application/json; charset=utf-8",数据类型:json",超时:10000,数据:JSON.stringify(params),成功:功能(响应){控制台日志(响应);}});

还有服务:

namespace myproject.frontend.Services{[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.ComponentModel.ToolboxItem(false)][脚本服务]公共类 SessionServices : System.Web.Services.WebService{[网络方法][ScriptMethod(ResponseFormat = ResponseFormat.Json)]公共字符串 HelloWorld(){返回你好世界";}}}

web.config:

<system.web><编译调试="true" targetFramework="4.0"/></system.web></配置>

和回应:

<string xmlns="http://tempuri.org/">Hello World</string>

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

这是 Fiddler HTTP 跟踪:

REQUEST-------POST http://myproject.local/Services/SessionServices.asmx/HelloWorld HTTP/1.1主机:myproject.local用户代理:Mozilla/5.0(Windows NT 6.1;WOW64;rv:13.0)Gecko/20100101 Firefox/13.0.1接受:application/json, text/javascript, */*;q=0.01接受语言:en-gb,en;q=0.5接受编码:gzip、deflate连接:保持连接内容类型:应用程序/json;字符集=utf-8X-Requested-With: XMLHttpRequest参考:http://myproject.local/Pages/Test.aspx内容长度:2Cookie:ASP.NET_SessionId=5tvpx1ph1uiie2o1c5wzx0bz编译指示:无缓存缓存控制:无缓存{}回复-------HTTP/1.1 200 正常缓存控制:私有,最大年龄=0内容类型:文本/xml;字符集=utf-8服务器:Microsoft-IIS/7.5X-AspNet 版本:4.0.30319X-Powered-By: ASP.NET日期:2012 年 6 月 19 日,星期二 16:33:40 GMT内容长度:96<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">Hello World</string>

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

加上其他几篇一般文章.

解决方案

终于想通了.

应用代码与发布的一样正确.问题出在配置上.正确的 web.config 是:

<预><代码><配置><system.web><编译调试="true" targetFramework="4.0"/></system.web><system.webServer><处理程序><add name="ScriptHandlerFactory"动词="*" 路径="*.asmx"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"资源类型=未指定"/></处理程序></system.webServer></配置>

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

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

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

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

希望这可以帮助任何有同样问题的人.并感谢海报提供建议.

Why does this simple web service refuse to return JSON to the client?

Here is my client code:

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

And the service:

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>

And the response:

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

No matter what I do, the response always comes back as XML. How do I get the web service to return Json?

EDIT:

Here is the Fiddler HTTP trace:

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>

I have lost count of how many articles I have read now trying to fix this. The instructions are either incomplete or do not solve my issue for some reason. Some of the more relevant ones include (all without success):

Plus several other general articles.

解决方案

Finally figured it out.

The app code is correct as posted. The problem is with the configuration. The correct web.config is:

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

According to the docs, registering the handler should be unnecessary from .NET 4 upwards as it has been moved to the machine.config. For whatever reason, this isn't working for me. But adding the registration to the web.config for my app resolved the problem.

A lot of the articles on this problem instruct to add the handler to the <system.web> section. This does NOT work and causes a whole load of other problems. I tried adding the handler to both sections and this generates a set of other migration errors which completely misdirected my troubleshooting.

In case it helps anyone else, if I had ther same problem again, here is the checklist I would review:

  1. Did you specify type: "POST" in the ajax request?
  2. Did you specify contentType: "application/json; charset=utf-8" in the ajax request?
  3. Did you specify dataType: "json"in the ajax request?
  4. Does your .asmx web service include the [ScriptService] attribute?
  5. Does your web method include the [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute? (My code works even without this attribute, but a lot of articles say that it is required)
  6. Have you added the ScriptHandlerFactory to the web.config file in <system.webServer><handlers>?
  7. Have you removed all handlers from the the web.config file in in <system.web><httpHandlers>?

Hope this helps anyone with the same problem. and thanks to posters for suggestions.

这篇关于asp.net asmx Web 服务返回 xml 而不是 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆