我需要基于请求URL.To获得XML和JSON响应数据--实现我的要求--我在global.asax
中将这段代码行添加到API的Application_Start
方法中
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‘1’类型未能序列化内容类型'application/xml;charset=utf-8‘的响应体。
这就是内在的异常信息。
键入'DeleteAPI.Models.StudentModel‘,其数据契约名为'StudentModel:http://schemas.datacontract.org/2004/07/DeleteAPI.Models’,这是不需要的。如果您正在使用DataContractResolver或将任何类型静态地添加到已知类型列表中,请考虑使用DataContractSerializer -例如,使用KnownTypeAttribute属性或将它们添加到传递给序列化程序的已知类型列表中。
这是我的模范课叫学生的一部分。
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;
}
}
我如何解决这个错误,原因是什么?
发布于 2018-04-10 13:56:15
尝试将操作方法更改为:
[HttpGet]
public HttpResponseMessage Get(int isxmlorJson)
{
StudentPersistent tp = new StudentPersistent();
tp = //Get data from Business Layer
var data = new ObjectContent<StudentPersistent>(tp,
((isxmlorJson== 1) ? Configuration.Formatters.XmlFormatter :
Configuration.Formatters.JsonFormatter));
return new HttpResponseMessage()
{
Content = data
};
}
这是定义控制器的一般方法,可以删除application_start中的配置。
https://stackoverflow.com/questions/49754710
复制相似问题