我在asp.net上開發了一個web服務,我希望它返回一個json字符串而不是xml文件。我已經在我的代碼中設置了以下內容,並通過互聯網上的多個來源進行查看,並且我嘗試了但是「錯誤」不斷出現。Webservice返回xml而不是json如何解決?
dao.asmx
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getLosKPIDataYear()
{
List<Object> sqlObject = new List<Object>();
String connectionString = DAO.GetConnectionString();
string sqlQuery = string.Empty;
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
SqlConnection sqlConn = new SqlConnection(connectionString);
try
{
sqlQuery = "select LOSYearYear, LOSYearLOS from LOSYear";
sqlConn.Open();
SqlDataReader reader = null;
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConn);
reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
sqlObject.Add(new { LOSYearYear = reader["LOSYearYear"].ToString(), LOSYearLOS = reader["LOSYearLOS"].ToString() });
}}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
sqlConn.Close();
var resultData = new { e = sqlObject.ToArray() };
ContentResult result = new ContentResult();
result.Content = serializer.Serialize(resultData);
result.ContentType = "application/json";
String myResult = result.Content;
return myResult;
}
的web.config
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<system.webServer>
<handlers>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
<modules runAllManagedModulesForAllRequests="true"/>
<staticContent>
<mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
</staticContent>
</system.webServer>
我應該怎麼做才能解決這個問題?提前致謝!
我可以建議你切換到WCF服務?開始實施/使用RESTful服務有一個很好的例子。使用WCF你不需要做任何你自己的序列化。 http://msdn.microsoft.com/en-us/magazine/dd315413.aspx – 2013-04-08 09:11:13