【问题标题】:.Net core 2.1 OdataRout not working.Net core 2.1 OdataRout 不工作
【发布时间】:2018-08-12 22:17:49
【问题描述】:

我正在尝试为客户实现一个 ODataController,它能够为我提供查询模型的 uri http://localhost:1234/odata/v1/customers?$top=4

或使用以下方法根据 Id 获得一位客户

http://localhost:1234/odata/v1/customers/1

但无论我尝试什么,我都无法将参数传递给控制器​​上的操作/功能。

我的代码是这样的。

        app.UseMvc(routeBuilder =>
        {
            routeBuilder.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
            routeBuilder.MapODataServiceRoute("ODataRoutes", "odata/v1", modelBuilder.GetEdmModel(app.ApplicationServices));
            routeBuilder.EnableDependencyInjection();
        });

GetEdmModel 基本上是这样构建模型的:

        builder.EntitySet<Customer>("Customers")
                        .EntityType
                        .Filter() // Allow for the $filter Command
                        .Count() // Allow for the $count Command
                        .Expand() // Allow for the $expand Command
                        .OrderBy() // Allow for the $orderby Command
                        .Page() // Allow for the $top and $skip Commands
                        .Select()// Allow for the $select Command; 
                         .ContainsMany(x => x.Transactions)
                        .Expand();

在控制器本身我已经定义了属性路由

[Produces("application/json")]
[ODataRoutePrefix("v1/[controller]")]
public class CustomersController : ODataController
{

    [EnableQuery]
    public ActionResult<IQueryable<Customer>> GetCustomers()
    {
        try
        {
            return context.Set<Customer>();
        }
        catch (Microsoft.OData.ODataException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    [EnableQuery]
    public ActionResult<Customer> Get([FromODataUri] string id)
    {
        try
        {
            var customer = context.Set<Customer>().Where(r => r.CustomerId == id).SingleOrDefault();

我看到当我有 uri = http://localhost:1234/odata/v1/customers/1 时,它会传递给函数 Get([FromODataUri] string id) 但是 id 的值始终为空。我已经尝试定义[ODataRoute("{id}")],但即使这样也没有用。

【问题讨论】:

    标签: .net-core odata asp.net-core-2.1


    【解决方案1】:

    OData 与控制器名称一起使用。 将[ODataRoutePrefix("v1/[controller]")] 更改为[ODataRoutePrefix("v1/Customers")]

    string id 更改为string key

    【讨论】:

    • 我不确定您的建议是否正确。 [controller] 被替换为实际的控制器名称。另外我认为参数名称也是如此。
    • 有一个在 ODataRoutePrefix 中使用 [controller] 的 github 问题说它不起作用,但除此之外,您能否引用任何显示 [controller] 在 ODataRoute 中工作的参考资料? odata 路由约定的源代码使用 entityset/key 语法,我在 OData 路由模板中看到不支持 [controller]。甚至entityset 也用于匹配操作方法名称,而不是用于模板。 github.com/OData/WebApi/blob/…
    • 我正在构建一个帖子或 GH 问题列表,这些帖子或 GH 问题尝试在 OData 路由模板中使用 [controller]gist.github.com/yzorg/62b7180c954a2ffaf8dd0dc89d79dca3 请随意添加您的帖子,或者如果您点击了这个,请发表评论.
    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 2023-03-14
    • 2018-12-25
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多