Replies: 2 comments
-
I've scoured back through the code to be sure, but there is only a single place where If you use any of the following: [ApiVersion("1.0")]
[ApiVersion("1.0-preview.1")]
[ApiVersion("2023-04-01")] that will use the default If you use any of these: [ApiVersion(1.0)]
[ApiVersion(1.0, "preview.1")] it won't because there is nothing to parse. This should make sense because there is no way for an attribute to get access to the DI container. A static singleton would provide a way to access it, but that is an anti-pattern and you'd likely have to set one in the DI container and one as some static property or method. Furthermore, there could be scenarios where someone needs two different parsers for some reason which would then be impossible or very difficult. That doesn't mean you're out of luck. There are still several options: Option 1Use conventions over attributes to assign the API versions. This doesn't require any parsing. The parsing behavior is due to a limitation in how attributes work. The Option 2Extend the existing attributes. All of the built-in attributes can be extended and have namespace My.Code;
public sealed class ApiVersionAttribute : Asp.Versioning.ApiVersionAttribute
{
private static readonly CustomApiVersionParser Parser = new();
public ApiVersionAttribute( string version ) : base( Parser, version ) { }
} The compiler takes precedence of your namespaces when resolving types, which means Option 3The final option would be to implement a fully custom solution that is similar to Option 2. API Versioning doesn't care about specific attributes. It only cares about Hopefully that clears things up and provides some approaches to close the gap on implementing custom parsing. |
Beta Was this translation helpful? Give feedback.
-
This was great! It got me unblocked. Thank you for mentioning that Attributes are a bit out of the scope of the DI. Working with Option 2 right now, as it seems to be moving me along. Digging through what the override methods all now need to be. O_O |
Beta Was this translation helpful? Give feedback.
-
I'm looking to use a custom string format for the API Versioning in our service, and I'm stuck.
To get off the ground, I've extended the built in Version/VersionFormatProvider/VersionReader classes, and am just tagging some breakpoints in these classes to validate they are being called.
I'm starting with the
ApiVersionParser
... I can register it (and see it function... sometimes..) with theservices.AddSingleton<IApiVersionParser, CustomApiVersionParser>();
command at the beginning of theConfigureServices
bootstrap... but it will ONLY fire with a valid and populated version parameter. If I specify any other version format string, it will not get called to parse the version format string. It seems the default version parser is still present somewhere in the call stack, validating the string before it gets to the provided Singleton...Beta Was this translation helpful? Give feedback.
All reactions