【问题标题】:asp.net WebApi: failed to serialize the response body for content type 'application/xml; charset=utf-8'asp.net WebApi:无法序列化内容类型“application/xml”的响应正文;字符集=utf-8'
【发布时间】:2020-02-28 19:53:01
【问题描述】:

当我尝试通过 http://localhost:XXXXX/api/Employees 访问 API 时收到此消息。我使用以下代码从数据库中获取数据,但 API 给了我以下错误

错误信息

> <Error> <Message>An error has occurred.</Message> <ExceptionMessage>
> The 'ObjectContent`1' type failed to serialize the response body for
> content type 'application/xml; charset=utf-8'. </ExceptionMessage>
> <ExceptionType>System.InvalidOperationException</ExceptionType>
> <StackTrace/> <InnerException> <Message>An error has
> occurred.</Message> <ExceptionMessage> Type
> 

>f__AnonymousType5`4 [System.String,System.String,System.String,System.String]'
> cannot be serialized. Consider marking it with the
> DataContractAttribute attribute, and marking all of its members you
> want serialized with the DataMemberAttribute attribute. If the type is
> a collection, consider marking it with the
> CollectionDataContractAttribute. See the Microsoft .NET Framework
> documentation for other supported types. </ExceptionMessage>
> <ExceptionType>
> System.Runtime.Serialization.InvalidDataContractException
> </ExceptionType>

这是我使用的代码

public IHttpActionResult GetEmployees()
        {
            var query = (from n in db.Employees
                         join c in db.tblCities on n.ProjectID equals c.CityID
                         into nc
                         from c in nc.DefaultIfEmpty()

                         join parent in db.Employees on n.ManagerName equals parent.Name
                        into pc
                         from parent in pc.DefaultIfEmpty()

                         select new
                         {
                             n.Name,
                             ManagerName = parent.Name,
                             n.Email,
                             c.CityName
                         });

            var employees = query.ToList();

            //some other things, maybe you want to return BadRequest if there are none or NotFound or whatever you deem appropriate
            return Ok(employees);
        }

【问题讨论】:

    标签: asp.net asp.net-web-api model-view-controller


    【解决方案1】:

    根据这个错误,你应该将你的类、函数和属性注释为DataContractAttributeDataMemberAttribute属性,以便序列化为xml。

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 2017-02-01
      • 2012-12-07
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多