0

在Web API 2.0中,我試圖從Get()方法返回IHttpActionResult。當我回來好吧(singleAnonymousObject)一切工作正常。但是,當我試圖返回確定(listOfAnonymousObject)我馬上得到錯誤。我還包括解釋上述情況的代碼。IHttpActionResult - 返回匿名對象列表

錯誤:

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

嘗試序列化爲XML時會引發此錯誤。如果不關心XML序列化並僅使用JSON - 指定_content-type:application/json_(例如郵遞員),它將按預期工作。 –

+1

謝謝。有效。或者我從'configuration.Formatters.XmlFormatter.SupportedMediaTypes'中刪除了XmlFormatter,現在只有JSon結果正在返回。 – user2243747

回答

0

網絡API 2支持這些行動的結果類型:

  • HttpResponseMessage

  • IHttpActionResult

  • Void

  • Other type

可能是,你可以使用其他類型和任務。

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