Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to hide metadata in web api 2, odata

I have defined odata route using MapODataServiceRoute in my WebApiConfig.

config.Routes.MapODataServiceRoute("CompanyoOdata", "odata", GetImplicitEdm(config));

private static IEdmModel GetImplicitEdm(HttpConfiguration config)
    {
        ODataModelBuilder builder = new ODataConventionModelBuilder(config, true);
        builder.EntitySet<Company>("Company");
        builder.EntitySet<Photo>("Photos");
        builder.EntitySet<Country>("Country");
        return builder.GetEdmModel();
    }

The data service works just fine. But I want to achieve few things.

I don't want to expose my metadata or associations because i'm using it internally and will not need metadata. How can I restrict access to these information (i.e restrict access to http://www.sample.com/odata/#metadata or http://www.sample.com/odata/$metadata)

secondly, I want to ignore some properties from getting serialized. I found two ways of doing this.

  1. Using data contracts and marking properties with [DataMember] attribute or [IgnoreDataMember] attribute
  2. Using Ignore method on EntitySet when building the model

I can't use the first method as I'm using Database first approach for entity framework hence can't decorate the entity with attributes. I thought I can achieve this by using MetaDataType, but it seems it only works for DataAnnotations.

I used second method with success, but you can't pass more than one property in the ignore method. Has to do it to individual property that I need to ignore, which is a bit tedious. Is there another way to do this?

any help really appreciated.

like image 304
Amila Avatar asked Dec 12 '22 03:12

Amila


1 Answers

If want to hide metadata (/$metadata) or service document (/), can remove the the MetadataRoutingConvention from existing routing conventions, e.g.:

var defaultConventions = ODataRoutingConventions.CreateDefault();
var conventions = defaultConventions.Except(
    defaultConventions.OfType<MetadataRoutingConvention>());
var route = config.MapODataServiceRoute(
    "odata",
    "odata",
    model,
    pathHandler: new DefaultODataPathHandler(),
    routingConventions: conventions);

If only expose a few properties per type, can use ODataModelBuilder instead of ODataConventionModelBuilder. E.g., some example:

ODataModelBuilder builder = new ODataModelBuilder();
EntityTypeConfiguration<Customer> customer = builder.EntitySet<Customer>("Customers").EntityType;
customer.HasKey(c => c.Id);
customer.Property(c => c.Name);
like image 53
Congyong Su Avatar answered Jan 02 '23 20:01

Congyong Su