Custom Odata v4 function - is not a valid odata route template - resource not found for the segment

NicoJuicy picture NicoJuicy · Oct 8, 2015 · Viewed 7.7k times · Source

I have something in mind like this ( the action on itself is probably okay)

    [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);
    }

The action defined in WebApiConfig would probably be something like this:

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

But i keep getting the following error ( after several rewrites)

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 

Any ideas what i'm doing wrong? I didn't find a lot of information online about odata and custom functions / actions except the ones on msdn.

Answer

Sam Xu picture Sam Xu · Oct 12, 2015

@NicoJuicy

Your code:

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

is to define a Bound function. A bound function is like the instance method that is called by instance.

Similar, the Uri template in ODataRoute should same as the bound function uri. So, it should be:

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

Besides, function is only used in GET scenario, So, [HttpPost] is not correct for function.

Maybe the following material can help you to understand the function/action in OData:

And the following materials can help you to understand the function/action parameters:

And the following materials can help you to understand the attribute routing: