Remove OData entity sets from $metadata endpoint

Viewed 131

I have an OData service built as .NET 5 web api, that exposes entity types and sets for different parts of the system- a public one for general data export and a "private" one that is used for internal applications.

Some of these entity sets are meant for the "private" part are not yet (or will never be) ready for public exposure. I have excluded them from Swagger and user would get 404 when trying accessing it with the authentication that is used in the public part of the service.

My issue is with $metadata endpoint that returns description about all the entity sets. So when a public user accesses the service, it sees entities that it should not.

Is there a way to exclude specific entity sets from the $metadata?

I've tried overriding ODataMetadataSerializer to exclude unwanted schema elements, but it does't allow manipulating the EDM model before generating the response.

1 Answers

You can register the EDM model dynamically, as per example on github.

The DynamicEdmModelCreation example was too complex for my case, were I needed to exclude just some entity sets (as in your case), so I changed only one thing from my static EdmModel: just call MapODataRoute method that takes in a delegate with IContainerBuilder instead of pre-created IEdmModel.

Here is example how I used it:

endpointBuilder.MapODataRoute ("odata", "odata/datasource/{dataSourceId:guid}/", builder =>
{
    builder
        .AddService (Microsoft.OData.ServiceLifetime.Scoped, provider =>
        {
            var serviceScope = provider.GetRequiredService<HttpRequestScope> ();
            return CreateMyEdmModelDynamicallyForRequest (serviceScope);
        })
        .AddService<IEnumerable<IODataRoutingConvention>> (Microsoft.OData.ServiceLifetime.Singleton, provider =>
            ODataRoutingConventions.CreateDefaultWithAttributeRouting ("odata", endpointBuilder.ServiceProvider));
});

The addition of IEnumerable<IODataRoutingConvention> is necessary because that is what MapODataRoute overloads with IEdmModel param do. Fails to resolve metadata endpoint without it for me.

Related