我想要实现接近于http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-actions
中描述的RateProduct操作的内容在该教程中,它被定义为:
[HttpPost]
public int RateProduct([FromODataUri] int key, ODataActionParameters parameters)
{
// ...
}
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Product>("Products");
// New Code
ActionConfiguration rateProduct = modelBuilder.Entity<Product>().Action("RateProduct");
rateProduct.Parameter<int>("Rating");
rateProduct.Returns<int>();
但是,我有一个Location实体的用例,它足够聪明,可以返回其周围某个半径范围内的其他位置。它大致应该是这样的:
[HttpPost]
public IQueryable<Location> GetLocationsWithinRadius([FromODataUri] int key, ODataActionParameters parameters)
{
// Get the Location instance intended to be the center of the radius by using the key
// Do a radius search around it using (int)parameters["radius"] as the radius
// return the IQueryable<Location> of all location found within that radius
}
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Location>("Locations");
// New Code
ActionConfiguration getLocations = modelBuilder.Entity<Location>().Action("GetLocationsWithinRadius");
getLocations.Parameter<int>("radius");
getLocations.Returns<IQueryable<Location>>();
我很想让这个工作起来,而且当返回类型是IQueryable<Location>
时它当前不起作用。如果返回类型是一个类似int的原语,那么它可以正常工作,否则当我在fiddler中创建一个帖子时会出现以下错误(帖子类似于http://localhost:2663/odata/Locations(2112)/GetLocationsWithinRadius
而请求正文是{radius: 50}
) :
{
"odata.error":{
"code":"","message":{
"lang":"en-US","value":"An error has occurred."
},"innererror":{
"message":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata=minimalmetadata; streaming=true; charset=utf-8'.","type":"System.InvalidOperationException","stacktrace":"","internalexception":{
"message":"The related entity set could not be found from the OData path. The related entity set is required to serialize the payload.","type":"System.Runtime.Serialization.SerializationException","stacktrace":" at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)\r\n at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.<>c__DisplayClassa.<WriteToStreamAsync>b__9()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)"
}
}
}
}
有可能做我想要完成的事吗?如果是的话,我敢问,返回的IQueryable<Location>
是否可以与odata paramaters组合......(那会很好)?
由于
答案 0 :(得分:19)
您的操作配置看起来不正确。尝试以下操作,看看它是否有效:
//getLocations.Returns<IQueryable<Location>>();
getLocations.ReturnsCollectionFromEntitySet<Location>("Locations");