Home > Enterprise >  Get key from Uri in CreateRef (.NET Core 6 OData)
Get key from Uri in CreateRef (.NET Core 6 OData)

Time:06-02

While upgrading to OData 8, could not find a way to fetch key from the URI for navigation property.

I'm using preview package of Asp.Versioning.OData and following this guide from Microsoft to fetch key from Uri. This guid has a method Helpers.GetKeyFromUri() but with OData v8, it has many extension methods missing such as GetUrlHelper() or types like KeyValuePathSegment.

Is there a new way to extract key from Uri when using Asp.Versioinng.OData with OData 8 and .net core 6?

I also referred to its source with examples but it did not implement how to fetch the key from Uri.

CodePudding user response:

@soccer7, the guide you are referring to is for OData with ASP.NET Web API (2.2). That does not apply to OData with ASP.NET Core.

The OData documentation doesn't appear to have been updated with how to extract the key. There may be other ways, but the following will definitely work:

[HttpPut]
public IActionResult CreateRef(
    int key,
    string navigationProperty,
    [FromBody] Uri link )
{
    var feature = HttpContext.ODataFeature();
    var model = feature.Model;
    var serviceRoot = new Uri( new Uri( feature.BaseAddress ), feature.RoutePrefix );
    var requestProvider = feature.Services;
    var parser = new ODataUriParser( model, serviceRoot, link, requestProvider );

    parser.Resolver ??= new UnqualifiedODataUriResolver() { EnableCaseInsensitive = true };
    parser.UrlKeyDelimiter = ODataUrlKeyDelimiter.Slash;

    var path = parser.ParsePath();
    var segment = path.OfType<KeySegment>().Single();
    var otherKey = segment.Keys.Single().Value; // note: could have multiple keys

    // TODO: use 'otherKey'

    return NoContent();
}

It took some spelunking, but this is based on what OData does to parse paths (as seen here). It's unclear why, but both the corresponding interface and implementation are marked internal. With a little extra work, you could turn this into an extension method.

  • Related