Search code examples
asp.net-core-mvcswaggerasp.net-core-webapiasp.net-core-3.1odata-v4

OData API Composite key and Swagger Settings


I Encounter an issue with Swagger.

I have a .Net Core Wep API with one entity using a composite key.

The key is declared with the following syntax:


public class EntityConfig : IModelConfiguration
    {
        public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
        {
            EntityTypeConfiguration<Entity> entity = builder.EntitySet<Entity>("Entity").EntityType;
            entity.HasKey(x => new { x.FirstId, x.SecondId});
        }
    }

My controller declare my delete API point like this :

[ODataRoutePrefix("Entity")]
public class EntityController : ODataController
{
///ctor with context injection

    [HttpDelete]
    public async Task<IActionResult> Delete([FromODataUri] int keyFirstId, [FromODataUri] int keySecondId)
    {
    ///Delete Behavior
    }

}

I can call my Delete method with Postman using this request : http://localhost:8090/api/Entity(FirstId=1,SecondId=1)

Eveything works with Postman and my website, but when i try to launch Swagger i get this error :

Microsoft.OData.ODataException: The number of keys specified in the URI does not match number of key properties for the resource.

How can i set Swagger to accept my parameters as composite key while keep working with OData ?

Thanks


Solution

  • Ok i finally find a solution.

    I have change my parameter into my controller and delete the 'key' prefix on my parameter.

    Then i have change my request by this version:

    http://localhost:8090/api/Entity(FirstId=0,SecondId=0)?FirstId=1&SecondId=1
    

    The request doesn't work without the first parameter declaration (FirstId=0,SecondId=0), i supposed that syntax force the parameter to by see as valid by my controller.

    Anyway, everything works and swagger doesn't complain anymore so i guess it's a good start.

    Thanks