问题
I have a working OData implementation with routes setup in the typical way:
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("People");
configuration.Routes.MapODataRoute(routeName:"OData", routePrefix:"odata", model:builder.GetEdmModel());
I'm looking for a way to programatically generate an absolute URL for a registered entity set from outside of any OData action. For example, I want to request the OData endpoint for the Person
type and get back "http://host/odata/People"
.
The standard URL helpers don't seem to apply since the OData routing is convention-based.
回答1:
You may want to leverage the IEdmModel instance generated by the ODataConventionModelBuilder.GetEdmModel().
IEdmModel model = builder.GetEdmModel(); // the builder is what you defined in the question.
var entitySetName = "";
foreach (var temp in model.FindEntityContainer("Container").EntitySets())
{
if (temp.ElementType.Name == "Person")
{
entitySetName = temp.Name;
break;
}
}
return "http://host/odata/"+entitySetName;
Note: if you define more than one entity set for an entity type, the upper code only returns the first one.
来源:https://stackoverflow.com/questions/22255143/how-do-i-generate-an-absolute-odata-url-for-a-given-entity-type