我在 asp.net 上开发了一个 Web 服务,我希望它返回一个 json 字符串而不是 xml 文件。我在我的代码中设置了以下内容,并查看了互联网上的多个来源,我尝试了但“错误”不断出现。
道.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;
}
网络配置
<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>
我应该怎么做才能解决这个问题?提前致谢!