【发布时间】:2014-10-08 08:02:58
【问题描述】:
我有一个使用 OData v4 的 Web Api 2.2 项目。正常的 EntitySet 配置对所有 http 动词都可以正常工作。我遇到问题的地方是尝试公开自定义函数。我开始尝试做一些与标准示例不同的事情,但我一直支持只是尝试让基本示例功能正常工作。
这是我的启动配置(直接来自 MS 示例):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
namespace Test.Service
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// other entitysets that don't have functions
builder.EntitySet<Product>("Products");
builder.Namespace = "ProductService";
builder.EntityType<Product>().Collection
.Function("MostExpensive")
.Returns<double>();
config.MapODataServiceRoute(
"odataroute"
, "odata"
, builder.GetEdmModel()
);
}
}
}
这是我的控制器:
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
namespace Test.Service.Controllers
{
public class ProductsController : ODataController
{
private EntityContext db = new EntityContext();
[EnableQuery]
public IQueryable<Product> GetProducts()
{
return db.Products;
}
[HttpGet]
public IHttpActionResult MostExpensive()
{
double test = 10.3;
return Ok(test);
}
}
}
常规的 GET,工作正常:
http://something/odata/Products
但是,以下总是给我一个 404:
http://something/odata/Products/ProductService.MostExpensive()
我在命名空间等方面尝试了许多不同的东西......所以,它不像所有示例那样工作,但我不知道如何深入挖掘以找出出错了。 http://something/odata 暴露的元数据没有提供任何线索。有没有其他方法可以发现这个函数应该在哪里(以及如何)暴露?
编辑:这是我关注的 Microsoft 示例的链接: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/odata-actions-and-functions
【问题讨论】:
-
只是好奇,你试过了吗:something/odata/Products/MostExpensive?
-
是的,我尝试了任意数量的不同组合:像 odata/Products/MostExpensive、odata/Products/MostExpensive()、odata/Products/Default.MostExpensive()(当我没有明确设置命名空间)
-
谢谢,我也注意到没有响应类型属性[ResponseType(typeof(decimal))]。
-
感谢您的建议,但 ResponseType 属性似乎在此版本的 WebApi 中不可用(或者我缺少使用...)。而且,在我看到的所有示例中,这不是必需的(我在上面的 MS 示例中添加了链接)。奇怪的是我可以毫无问题地添加一个未绑定的函数,我只是无法将函数绑定到实体集。
标签: c# asp.net-web-api odata asp.net-web-api-routing