我需要根据请求URL获取XML和JSON响应数据。为了满足我的需求,我在API中添加了这些代码行
Application_Start
中的方法
global.asax
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
这段代码可以很好地用于获取JSON。我这样调用API,
对于JSON输出:
http://localhost:2751/api/student?type=JSON
对于XML输出:
http://localhost:2751/api/student?type=xml
但是,当我调用XML时,会发生此错误。
ObjectContent“1”类型未能序列化的响应正文
“内容类型”应用程序/xml;字符集=utf-8’。
这是内部异常消息。
键入“DeleteAPI”。型号。带数据的StudentModel
合同名称
'学生模型:
http://schemas.datacontract.org/2004/07/DeleteAPI.Models
'
不应为。如果需要,请考虑使用DataContractResolver
使用DataContractSerializer或将任何静态未知类型添加到
已知类型的列表-例如,通过使用KnownTypeAttribute
属性,或将其添加到传递给
序列化程序。
这是我的模型课call Student的一部分。
public class StudentModel
{
public int StudentID { get; set; }
public int ProjectID { get; set; }
public string WorkDate { get; set; }
public Nullable<int> WorkingHours { get; set; }
public Nullable<int> Overtime { get; set; }
public string Descriptions { get; set; }
}
控制器类的一部分,
namespace DeleteAPI.Controllers
{
public class StudentController : ApiController
{
// GET: api/Student
public ArrayList Get()
{
StudentPersistent tp = new StudentPersistent();
return tp.getStudentAll();
}
}
}
这是
StudentPersistent.class
public class StudentPersistent
{
public ArrayList getStudentAll()
{
ArrayList stdArray = new ArrayList();
MySql.Data.MySqlClient.MySqlDataReader mySQLReader = null;
try
{
string sqlString = "select * from tblStudent";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
mySQLReader = cmd.ExecuteReader();
while (mySQLReader.Read())
{
StudentModel dm = new StudentModel();
dm.StudentID = mySQLReader.GetInt32(0);
dm.ProjectID = mySQLReader.GetInt32(1);
dm.WorkDate = mySQLReader.GetString(2);
dm.WorkingHours = mySQLReader.GetInt32(3);
dm.Overtime = mySQLReader.GetInt32(4);
dm.Descriptions = mySQLReader.GetString(5);
stdArray.Add(dm);
}
}
catch (MySqlException x)
{
Console.WriteLine(x.Number);
}
return stdArray;
}
}
如何解决此错误,原因是什么?