【问题标题】:Error occurred when returning XML - ASP.net web API返回 XML 时发生错误 - ASP.net Web API
【发布时间】:2018-04-10 13:17:24
【问题描述】:

我需要根据请求 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; charset=utf-8'。

这是内部异常消息。

键入带有数据的“DeleteAPI.Models.StudentModel” 合同名称 '学生模型:http://schemas.datacontract.org/2004/07/DeleteAPI.Models' 预计不会。如果您是,请考虑使用 DataContractResolver 使用 DataContractSerializer 或添加任何静态未知的类型 已知类型的列表 - 例如,通过使用 KnownTypeAttribute 属性或通过将它们添加到传递给 序列化器。

这是我的模型类调用 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; }
}

Controller类的一部分,

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;
    }
}

我该如何解决这个错误,它的原因是什么?

【问题讨论】:

    标签: c# json xml asp.net-web-api serialization


    【解决方案1】:

    尝试将操作方法​​更改为:

    [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中的配置可以去掉。

    【讨论】:

    • 你能给我示例代码吗?如何编写方法体。
    • 嗨,谢谢你的回答。但不幸的是,发生了这个错误。 Error CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Net.Http.Formatting.XmlMediaTypeFormatter' and 'System.Net.Http.Formatting.JsonMediaTypeFormatter'
    • 还有一个问题。根据您的回答,我不得不像这样调用 API http://localhost:2751/api/student/1。根据我的项目,我不能以这种方式调用 API。我需要通过调用 API http://localhost:2751/api/student?type=JSONhttp://localhost:2751/api/student?type=XMLhttp://localhost:2751/api/student.jsonhttp://localhost:2751/api/student.xml 来获取 JSONXML 输出
    【解决方案2】:

    问题解决了。我在模型类中添加了KnownType 属性。

    [KnownType(typeof(DeleteAPI.Models.TaskModel))]
    public class StudentModel
    {
        public int DeveloperID { 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; }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 1970-01-01
      • 2013-01-14
      • 2020-07-10
      • 2017-05-28
      • 1970-01-01
      • 2015-08-17
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多