【问题标题】:Custom Odata v4 function - is not a valid odata route template - resource not found for the segment自定义 Odata v4 功能 - 不是有效的 odata 路由模板 - 未找到该段的资源
【发布时间】:2016-01-06 14:35:08
【问题描述】:

我有这样的想法(对自己的操作可能还可以)

    [HttpPost]
    [ODataRoute("GenerateFromProduct")]
    public async Task<IHttpActionResult> GenerateFromProduct([FromBodyAttribute] Product product)
    {
        if(!ModelState.IsValid)
        {
            return BadRequest();
        }

        List<string[]> combos = new List<string[]>();
        List<ProductVariant> productVariants = product.GenerateProductVariants();
        db.ProductVariants.AddRange(productVariants);

        await db.SaveChangesAsync();

        return Ok(productVariants);
    }

WebApiConfig 中定义的动作大概是这样的:

 builder.EntityType<ProductVariant>().Collection
 .Function("GenerateFromProduct").Returns<List<ProductVariant>>().EntityParameter<Product>("product");

但我不断收到以下错误(经过多次重写)

An exception of type 'System.InvalidOperationException' occurred in System.Web.OData.dll but was not handled in user code

Additional information: The path template 'GenerateFromProduct' on the action 'GenerateFromProduct' in controller 'ProductVariants' is not a valid OData path template. Resource not found for the segment 

任何想法我做错了什么?除了 msdn 上的之外,我没有在网上找到很多关于 odata 和自定义函数/操作的信息。

【问题讨论】:

    标签: .net asp.net-mvc asp.net-web-api odata odata-v4


    【解决方案1】:

    @NicoJuicy

    您的代码:

    builder.EntityType<ProductVariant>().Collection.Function("GenerateFromProduct")...
    

    是定义一个Bound函数。绑定函数类似于由实例调用的实例方法

    类似,ODataRoute 中的 Uri 模板应该与绑定函数 uri 相同。所以,应该是:

     [ODataRoute("ProductVariants/YourNameSpace.GenerateFromProduct(product={product}")]
    

    另外,函数只用于GET场景,所以[HttpPost]不适合函数。

    也许以下材料可以帮助您理解 OData 中的功能/动作:

    以下材料可以帮助你理解函数/动作参数:

    以下材料可以帮助你理解属性路由:

    【讨论】:

    • 我确实在路由上取得了一些进展(制作了第一个函数 - 绑定和未绑定,但我在 stackoverflow.com/questions/33137197/… 上有一个后续问题。我认为这个答案是有效的,因为我对函数中的路由和配置仍然有些限制。我现在知道绑定函数期望返回一个实体(或模型)。仍然很奇怪,需要在 WebApiConfig 中单独声明 odataController 函数/操作,除非它是也在模特身上
    • 附言。我在文档和/或 github 上缺少一些实际示例。例如。我还没有找到如何声明一个可选参数来处理类似 [ODataRoute("Products({key})/GenerateVariants({save?}")] 的路由的方法。我不想听起来忘恩负义,odata 摇滚,但有些事情还不清楚:-)
    • 不支持可选参数。但是,您可以定义一个参数是可为空的。例如int?.
    猜你喜欢
    • 2017-03-23
    • 2018-08-25
    • 2017-05-20
    • 2019-04-13
    • 2015-11-03
    • 1970-01-01
    • 2015-03-05
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多