Search code examples
c#attributes

Set the ApiExplorerSettingsAttributes value dynamically


Since a lot of attributes are designed by avoid unsealed attributes I'm searching for a solution for setting an attributes value (my first idea was to inherit the class and set a constructor what checks the web-config - not possible with a sealed class):

There's the ApiExplorerSettingsAttribute in namespace System.Web.Http.Description

I want the following API-action to get hidden in the case, a value in web-config is false:

<Api.Properties.Settings>
  <setting name="Hoster">
    <value>False</value>
  </setting>
</Api.Properties.Settings>

the action would look like this:

[HttpGet, Route("api/bdlg")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(BdlgDataStorage))]
[ApiExplorerSettings(IgnoreApi = Properties.Settings.Default.Hoster)]
private async Task<BdlgDataStorage> GetBdlgStorageValues()
{
    using (var context = new BdlgContext())
        return context.BdlgDataStorages
            .Include(s=>s.ChangeTrack)
            .Where(w=>w.Isle > 56)
            .Select(selectorFunction)
            .ToListAsync();
}

The important line is:

[ApiExplorerSettings(IgnoreApi = Properties.Settings.Default.Hoster)]

Here, I get a compiler-error:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Anyone got any idea, how I can set the value of IgnoreApi the same as the one from web-config?


Solution

  • You can't. Attributes are compiled statically into the assembly. They belong to the metadata of a member. You can't change attributes at run-time.

    You have to find another way to influence the ApiExplorerSettings. This post seems to be what you are looking for: Dynamically Ignore WebAPI method on controller for api explorer documentation.