CodeExplorer
CodeExplorer

Reputation: 113

Dynamically Ignore WebAPI method on controller for api explorer documentation

we have implemented a webAPI and we have a number of API controllers. We provide an API documentation for our API and what we want to do is to exclude certain web methods from the documentation but we want this to be done dynamically depending on the environment we are running. just to give you an understanding of what I mean, let's say I have the following web method

[ApiExplorerSettings(IgnoreApi = true)] 
public Product getProduct()
{
   ...
}

By setting the IgnoreAPI property on the ApiExplorerSettingAttribute to true, it excludes the web method from the documentation which is what we want but we need a way of setting the "true" value dynamically. Ideally we would like to have a database table with bool values for each webMethod and based on these set the value for IgnoreAPi property. Is there a way to achieve this? Your help will be much appreciated.

Upvotes: 11

Views: 18700

Answers (2)

Eilon
Eilon

Reputation: 25704

You can implement a custom IApiExplorer and register it in Web API's services to have full control over which APIs are listed or not.

Here's a blog post from the dev who implemented most of this: https://learn.microsoft.com/en-us/archive/blogs/yaohuang1/asp-net-web-api-introducing-iapiexplorerapiexplorer

And here's the IApiExplorer interface definition: http://msdn.microsoft.com/en-us/library/system.web.http.description.iapiexplorer(v=vs.118).aspx

One thing you could do is derive from (or re-use the existing source of) the existing ApiExplorer implementation and call base to get the default list, and then further filter it however you want.

And per s_hewitt's comment, the recommendation is:

Deriving from ApiExplorer, implementing the two methods ShouldExploreAction and ShouldExploreController is the way to go. Make your DB calls in those two methods, looking up based on route, controller and action.

Upvotes: 14

Josh Gallagher
Josh Gallagher

Reputation: 5329

I don't know much about the documentation generation of WebAPI, but I do know about attributes. Attributes are compiled into the code and result in hard coded values being held in directly in the data in the EXE or DLL. They cannot be changed.

Having said that, you might be able to apply attributes as a second set after normal compilation. Perhaps PostSharp could help here? Perhaps changing the solution configuration could be a way of indicating the environment you want to build for and this which methods get the IgnoreApi treatment. You could create your own attribute to apply to the methods that describes which environments the method should be ignored within. (I think it's more likely you'll be able to do what you want in PostSharp if you don't try and call a database to get hold of this data.)

Upvotes: 0

Related Questions