asp.net WebApi:未能序列化内容类型';应用程序/xml;字符集=utf-8';

asp.net WebApi:未能序列化内容类型';应用程序/xml;字符集=utf-8';,asp.net,asp.net-web-api,model-view-controller,Asp.net,Asp.net Web Api,Model View Controller,当我尝试通过访问API时,会收到此消息。我使用以下代码从数据库获取数据,但API给了我以下错误 错误消息 > <Error> <Message>An error has occurred.</Message> <ExceptionMessage> > The 'ObjectContent`1' type failed to serialize the response body for > content type 'applic

当我尝试通过访问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>

根据此错误,您应该将类、函数和属性注释为
DataContractAttribute
DataMemberAttribute
属性,以便序列化为xml

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