1
votes

I am trying to enable CORS on my webapi so i can consume it from another project using breezejs. In my webapi i have enabled OData V4 and created an edm model for breeze to consume like so:

ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<ModuleEntity>("ModuleEntities");
builder.EntitySet<DomainEntity>("DomainEntities");
builder.EntitySet<ApiUserEntity>("ApiUserEntities");

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: "",
    model: builder.GetEdmModel());

all three entitysets have their own controller deriving from odatacontrollers.

I have enabled cors in my webapi like so:

// see http://stackoverflow.com/questions/18032360/cors-using-asp-net-web-api-2-odata-and-breeze for last 2 parameters
var cors = new EnableCorsAttribute("*", "*", "*", "DataServiceVersion, MaxDataServiceVersion"); // origins, headers, methods
config.EnableCors(cors);

When i try to access localhost:22594/$metadata i get the correct xml back containing the EDM model data configured above.

From my webproject using breezejs with Firefox however i get the message that cors is not enabled when it tries to query localhost:22594/$metadata and that i am not allowed to read it from that origin.

I am executing breeze queries likes so:

// setup dataservice
this.dataService = new this.breeze.DataService({
    serviceName: "http://localhost:22594/"
 });

// initialize adapter with OData as dataservice
this.breeze.config.initializeAdapterInstances({ dataService: "OData" });
this.manager = new this.breeze.EntityManager({ dataService: this.dataService });

// query ApiUser entity
var query = this.breeze.EntityQuery().from("ApiUser");

// execute query 
this.manager.executeQuery(query);

I am still new to breezejs so right now i dont know if my error lies in the usage of breezejs or my webaopi configuration. I have tried alot of things but i cant seem to figure out what i am doing wrong.

1

1 Answers

2
votes

I may have found the solution already. First, i had to switch back to odata v3. Turns out that breezejs/datajas is not yet compatible with v4.

After that i faced a new error message, saying it could not read 'end' of null. Could not find anything about that message either so experimented a bit. Turns out that all of my model classes were in their own respective folders. which ment i was using a different namespaces for each entity.

From the breezejs documentation: (http://www.getbreezenow.com/documentation/odata-server)

You are stuck if your model classes have more than one namespace. As far as we know, Web API OData cannot handle model classes located in multiple namespaces.

I placed every entity in the same folder so that they were all using the same namespace and voila! I can now finally query my webapi with breezejs using odata!