asp.net asmx web服务返回xml而不是json

njr*_*101 50 c# asp.net json web-services asmx

为什么这个简单的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);
            }
        });
Run Code Online (Sandbox Code Playgroud)

和服务:

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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

web.config中:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)

并回应:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>
Run Code Online (Sandbox Code Playgroud)

无论我做什么,响应总是以XML形式返回.如何让Web服务返回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>
Run Code Online (Sandbox Code Playgroud)

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

还有其他几篇一般文章.

njr*_*101 44

终于想通了.

已发布的应用代码正确无误.问题在于配置.正确的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>
Run Code Online (Sandbox Code Playgroud)

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

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

万一它可以帮助其他人,如果我再次遇到同样的问题,这里是我要检查的清单:

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

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


小智 27

以上解决方案没有成功,这里我是如何解决的.

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

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

  • 你做到了!这是最好的答案.我使我的函数成为一个"void"返回类型并使用了您的代码,并且JQuery UI自动完成最终开始工作. (7认同)

Kal*_*sai 12

如果您希望继续使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

从Web服务返回纯字符串有更简单的方法.我把它称为CROW功能(让它易于记忆).

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

如您所见,返回类型为"void",但CROW函数仍将返回您想要的值.