Created
September 28, 2015 15:34
-
-
Save bryan-c-oconnell/4fb7a0605553eea2cbf8 to your computer and use it in GitHub Desktop.
bryanoconnell.blogspot.com - Easily expose metadata information from Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Written by Bryan O'Connell, June 2015 | |
// http://bryanoconnell.blogspot.com/2015/08/easily-expose-metadata-info-from-webapi.html | |
// Purpose: Example of how to configure routes to expose metadata information | |
// about specific objects in your API. | |
using System; | |
using System.Web.Http; | |
using System.Web.Http.OData.Builder; | |
using System.Web.Http.OData.Extensions; | |
using Microsoft.Data.Edm; | |
// NOTE: You'll need to add 'using' statements here to include the Models | |
// to be mapped below. | |
namespace BOC.SampleAPI | |
{ | |
public static class WebApiConfig | |
{ | |
public static void Register(HttpConfiguration config) | |
{ | |
// Web API routes | |
config.MapHttpAttributeRoutes(); | |
config.Routes.MapHttpRoute( | |
name: "DefaultApi", | |
routeTemplate: "{controller}/{id}", | |
defaults: new { id = RouteParameter.Optional } | |
); | |
// Step 1 - Convert your Class into an EDM Model. | |
var ModelOf_SomeClass = BuildModel<SomeClass>("SomeClass"); | |
// Step 2 - Create a new route that will return metadata information about the Model. | |
config.Routes.MapODataServiceRoute( | |
"Metadata-SomeClass", // Friendly name for the new route (not externally visible) | |
"Entities/SomeClass", // URI for the new route | |
ModelOf_SomeClass // Model to expose | |
); | |
// The following should now return metadata information for the specified Model: | |
// - http://yourapi.com/Entities/SomeClass/$metadata | |
// Step 3 - Repeat this for each Class for which you want to expose metadata information. | |
} | |
// Converts a Class into an EDM Model. | |
private static IEdmModel BuildModel<T>(string EntityName) where T : class | |
{ | |
ODataConventionModelBuilder ODataBuilder = new ODataConventionModelBuilder(); | |
ODataBuilder.EntitySet<T>(EntityName); | |
return ODataBuilder.GetEdmModel(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment