IHttpActionResult - 返回匿名对象列表

时间:2016-09-24 12:30:35

标签: rest asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

在Web API 2.0中,我尝试从Get()方法返回 IHttpActionResult 。当我返回 Ok(singleAnonymousObject) 时,一切正常。但是,当我尝试返回 OK(listOfAnonymousObject) 时,我得到以下错误。我还包括用于解释上述场景的代码。

错误:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type '<>f__AnonymousType0`2[System.Int32,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>
<StackTrace>
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.XmlObjectSerializerContext.GetDataContract(Int32 id, RuntimeTypeHandle typeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at WriteArrayOf_x003C__x003E_f__AnonymousType0OfintstringToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()
</StackTrace>
</Error>

以下是我的设置。

Web API配置:

public void Configuration(IAppBuilder app)
    {
        HttpConfiguration configuration = new HttpConfiguration();

        configuration.Routes.MapHttpRoute("DefaultRoute","api/{controller}/{id}",new  {id = RouteParameter.Optional});

        var container = new UnityContainer();
        container.RegisterType<IUnitOfWork, ProductUOW>();
        container.RegisterType<ProductContext, ProductContext>();
        configuration.DependencyResolver = new UnityDependencyResolver(container);

        app.UseWebApi(configuration);
    }

ValuesController

public IHttpActionResult Get()
        {
            var r = productUow.Customers.Get();
            var result = r.Where(rr => rr.Id > 0).Select(n => new
            {
                IdVal = n.Id,
                TEstName = n.Name
            }).FirstOrDefault();
            return Ok(result);
        }

在调用 http://localhost:61569/api/values 后,我将获得单个JSon对象。但是当我尝试返回列表时,我收到了上述错误消息。

问题

public IHttpActionResult Get()
{
     var r = productUow.Customers.Get();
     var result = r.Where(rr => rr.Id > 0).Select(n => new
     {
          IdVal = n.Id,
          TEstName = n.Name
     }).ToList(); //Causing trouble here
     return Ok(result);
}

1 个答案:

答案 0 :(得分:0)

Web Api 2支持这些操作结果类型:

  • HttpResponseMessage

  • IHttpActionResult

  • Void

  • Other type

可能,您可以使用其他类型和任务。

[HttpGet]
public async Task<CustomResponseModel> Test()
{
  .
  .
  .
}