C# asp.net asmx Web 服务返回 xml 而不是 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11088294/
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
asp.net asmx web service returning xml instead of json
提问by njr101
Why does this simple web service refuse to return JSON to the client?
为什么这个简单的 Web 服务拒绝将 JSON 返回给客户端?
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?
无论我做什么,响应总是以 XML 形式返回。如何让 Web 服务返回 Json?
EDIT:
编辑:
Here is the Fiddler HTTP trace:
这是 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>
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):
我已经不知道我现在阅读了多少试图解决这个问题的文章。这些说明要么不完整,要么由于某种原因无法解决我的问题。一些更相关的包括(都没有成功):
- ASP.NET web service erroneously returns XML instead of JSON
- asmx web service returning xml instead of json in .net 4.0
- http://williamsportwebdeveloper.com/cgi/wp/?p=494
- http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
- http://forums.asp.net/t/1054378.aspx
- http://jqueryplugins.info/2012/02/asp-net-web-service-returning-xml-instead-of-json/
- ASP.NET Web 服务错误地返回 XML 而不是 JSON
- asmx Web 服务在 .net 4.0 中返回 xml 而不是 json
- http://williamsportwebdeveloper.com/cgi/wp/?p=494
- http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
- http://forums.asp.net/t/1054378.aspx
- http://jqueryplugins.info/2012/02/asp-net-web-service-returning-xml-instead-of-json/
Plus several other general articles.
加上其他几篇一般文章。
采纳答案by njr101
Finally figured it out.
终于想通了。
The app code is correct as posted. The problem is with the configuration. The correct web.config is:
应用程序代码与发布的一样正确。问题出在配置上。正确的 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>
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.
根据文档,从 .NET 4 开始,注册处理程序应该是不必要的,因为它已移至 machine.config。无论出于何种原因,这对我不起作用。但是将注册添加到我的应用程序的 web.config 解决了这个问题。
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.
很多关于这个问题的文章都指示将处理程序添加到该<system.web>部分。这不起作用,并导致大量其他问题。我尝试将处理程序添加到这两个部分,这会生成一组其他迁移错误,这些错误完全误导了我的故障排除。
In case it helps anyone else, if I had ther same problem again, here is the checklist I would review:
如果它对其他人有帮助,如果我再次遇到同样的问题,这里是我要查看的清单:
- Did you specify
type: "POST"in the ajax request? - Did you specify
contentType: "application/json; charset=utf-8"in the ajax request? - Did you specify
dataType: "json"in the ajax request? - Does your .asmx web service include the
[ScriptService]attribute? - 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) - Have you added the
ScriptHandlerFactoryto the web.config file in<system.webServer><handlers>? - Have you removed all handlers from the the web.config file in in
<system.web><httpHandlers>?
- 你
type: "POST"在ajax请求中指定了吗? - 你
contentType: "application/json; charset=utf-8"在ajax请求中指定了吗? - 你
dataType: "json"在ajax请求中指定了吗? - 您的 .asmx Web 服务是否包含该
[ScriptService]属性? - 您的网络方法是否包含该
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]属性?(我的代码即使没有这个属性也能工作,但是很多文章都说是必须的) - 你有没有添加
ScriptHandlerFactory到 web.config 文件中<system.webServer><handlers>? - 您是否从 in 中的 web.config 文件中删除了所有处理程序
<system.web><httpHandlers>?
Hope this helps anyone with the same problem. and thanks to posters for suggestions.
希望这可以帮助任何有同样问题的人。并感谢海报提供建议。
回答by j0aqu1n
For me it works with this code I got from this post:
对我来说,它适用于我从这篇文章中得到的代码:
如何使用 Json.Net 从我的 WCF 休息服务 (.NET 4) 返回 json,而不是用引号括起来的字符串?
[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);
}
回答by Ajay
No success with above solution, here how I resolved it.
上述解决方案没有成功,这里是我如何解决它。
put this line into your webservice and rather return type just write the string in response context
将此行放入您的网络服务中,而返回类型只需在响应上下文中写入字符串
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serial.Serialize(city));
回答by smoore4
I have a .asmx web service (.NET 4.0) with a method that returns a string. The string is a serialized List like you see in many of the examples. This will return json that is not wrapped in XML. No changes to web.config or need for 3rd party DLLs.
我有一个 .asmx Web 服务 (.NET 4.0),其中包含一个返回字符串的方法。字符串是一个序列化的 List,就像您在许多示例中看到的那样。这将返回未包装在 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;
The client part that uses the service looks like this:
使用该服务的客户端部分如下所示:
$.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);
}
});
回答by Kalpesh Desai
If you want to stay remain with Framework 3.5, you need to make change in code as follows.
如果您想继续使用 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);
}
}
回答by Arindam Nayak
I have tried all of the above steps ( even the answer), but i was not successful, my system configuration is Windows Server 2012 R2, IIS 8. The following step solved my problem.
我已经尝试了上述所有步骤(甚至是答案),但我没有成功,我的系统配置是 Windows Server 2012 R2,IIS 8。以下步骤解决了我的问题。
Changed the app pool, that has managed pipeline = classic.
更改了管理管道 = 经典的应用程序池。
回答by GabrielJ
There is much easier way to return a pure string from web service. I call it CROW function (makes it easy to remember).
从 Web 服务返回纯字符串的方法要简单得多。我称它为 CROW 函数(便于记忆)。
[WebMethod]
public void Test()
{
Context.Response.Output.Write("and that's how it's done");
}
As you can see, return type is "void", but CROW function will still return the value you want.
如您所见,返回类型为“void”,但 CROW 函数仍将返回您想要的值。
回答by Mohamed.Abdo
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;
回答by Sebastian Siewień
I know that is really old question but i came to same problem today and I've been searching everywhere to find the answer but with no result. After long research I have found the way to make this work. To return JSON from service you have provide data in request in the correct format, use JSON.stringify()to parse the data before request and don't forget about contentType: "application/json; charset=utf-8", using this should provide expected result.
我知道这真的是个老问题,但我今天遇到了同样的问题,我一直在到处寻找答案,但没有结果。经过长时间的研究,我找到了使这项工作的方法。要从服务返回 JSON,您以正确的格式在请求中提供数据,请使用JSON.stringify()在请求之前解析数据并且不要忘记 about contentType: "application/json; charset=utf-8",使用它应该提供预期的结果。
回答by Otto
Hope this helps, it appears that you still have to send some JSON object in the request, even if the Method you are calling has no parameters.
希望这会有所帮助,即使您正在调用的方法没有参数,您似乎仍然需要在请求中发送一些 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;
});

