C# · 12月 31, 2021

c# – .Net WebApi OData返回Queryable的操作

我想要实现一些接近RateProduct的动作,描述如下: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-actions

在该教程中,它被定义为:

[HttpPost]public int RateProduct([FromODataUri] int key,ODataActionParameters parameters) { // …}ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();modelBuilder.EntitySet<Product>(“Products”);// New CodeActionConfiguration rateProduct = modelBuilder.Entity<Product>().Action(“RateProduct”);rateProduct.Parameter<int>(“rating”);rateProduct.Returns<int>();

但是,我有一个位置实体的用例,足够聪明地返回其周围的某个半径的其他位置.大概应该是这样的:

[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 CodeActionConfiguration 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 …(那将是很好)

谢谢

解决方法 看起来你的动作配置不正确.尝试以下内容,看看它是否有效: //getLocations.Returns<IQueryable<Location>>();getLocations.ReturnsCollectionFromEntitySet<Location>(“Locations”);