为什么这个简单的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。 如何获取Web服务返回JSON?
编辑:
这里是小提琴手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>
我已经记不清有多少文章我看了,现在试图解决这一问题计数。 该指令是不完整或不解决我的问题,因为某些原因。 一些更相关者包括(均无功而返):
- ASP.NET Web服务错误地返回XML而不是JSON
- 在.NET 4.0中ASMX Web服务返回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/
加上其他一些普通物品。
Answer 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>
根据该文档,因为它已被移动到在machine.config注册处理程序应该从.NET 4向上不必要的。 无论出于何种原因,这不是为我工作。 但是,增加注册到Web.config我的应用程序解决了这个问题。
很多在这个问题上的文章的指示到处理程序添加到<system.web>
部分。 这并不工作,并导致其他问题的整体负载。 我尝试添加的处理程序两部分,这产生一组完全误导我的故障排除其他迁移错误的。
在情况下,它可以帮助别人,如果我再有疗法同样的问题,这里是我的清单会检讨:
- 你指定
type: "POST"
在Ajax请求? - 你指定
contentType: "application/json; charset=utf-8"
在Ajax请求? - 你指定
dataType: "json"
在Ajax请求? - 请问您的.asmx Web服务包括
[ScriptService]
属性? - 您的Web方法包括
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
属性? (我的代码工作,即使没有这个属性,但很多文章说,这是必需的) - 你已经添加了
ScriptHandlerFactory
到web.config文件中<system.webServer><handlers>
? - 你是否从web.config文件中的所有处理中
<system.web><httpHandlers>
?
希望这有助于同样的问题的人。 并感谢海报建议。
Answer 2:
与上述方案没有成功,在这里我怎么解决它。
把此行到您的互联网服务和宁愿返回类型只是写在响应上下文字符串
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serial.Serialize(city));
Answer 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);
}
}
Answer 4:
还有更容易返回从Web服务的纯字符串的方式。 我把它叫做乌鸦功能(可以很容易地记住)。
[WebMethod]
public void Test()
{
Context.Response.Output.Write("and that's how it's done");
}
正如你所看到的,返回类型是“无效的”,但CROW功能仍然会返回所需的值。
Answer 5:
我有一个返回字符串的方法的.asmx Web服务(.NET 4.0)。 该字符串是一个序列化的列表就像你在许多例子中看到。 这将返回的JSON不裹XML。 没有改变的web.config或需要第三方的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);
}
});
Answer 6:
对我来说,它的工作原理与此代码我这个职位的了:
我怎样才能返回JSON从我的WCF REST服务(.NET 4),使用Json.Net,没有它是一个字符串,包裹在引号?
[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);
}
Answer 7:
我已经尝试了所有上述步骤(甚至答案),但我没有成功,我的系统配置是Windows Server 2012中R2,IIS 8.下列步骤解决我的问题。
改变了应用程序池,已托管管道=经典。
Answer 8:
我知道这是真的老问题,但我今天来到了同样的问题,我一直在到处搜寻,希望找到答案,但没有结果。 经过长期的研究,我发现,使这项工作的方式。 要从服务返回JSON你必须在正确的格式要求提供数据,使用JSON.stringify()
来解析请求之前的数据,不要忘记contentType: "application/json; charset=utf-8"
,使用此应提供预期的结果。
Answer 9:
希望这可以帮助,看来你还是送一些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;
});
Answer 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;
文章来源: asp.net asmx web service returning xml instead of json