c# - How can versioning be done in ASP.NET Core Web Api -
in previous asp.net web api
, implement defaulthttpcontrollerselector
specify how want request locate controller. have different controllers different names intended same processes. difference 1 of higher version other.
for example, have controller named bookingv1controller
, meant handle version 1 of service. have bookingv2controller
, designed handle version 2 of service. client application make request service url http://myservice.com/api/v2/booking/someaction?id=12
. handle request, provide custom implementation of defaulthttpcontrollerselector
select appropriate version of controller required based on requested version.
however, seems not have way in asp.net core
. have searched everywhere no avail. no documentation either.
i appreciate if can of me here. thanks.
update know if version specified in custom header. e.g x-version:v1
update 2
the requirement version of service should not exposed in url. if no version present, service returns instruction on how add version. if requested controller not present in version requested, system searches through lower versions. if finds in lower versions, uses that. reason prevent repetition of controllers on versions. asp.net core, might not possible.
i created package purpose after banging head on problem few days. doesn't require attributes.
https://github.com/goaheadtours/namespaceversioning
in summary, can register iapplicationmodelconvention in startup file can iterate through controllers , register routes based on namespaces. created v1 folder, , put controller inside
the class implements iapplicationmodelconvention implements apply method applicationmodel parameter have access controllers in app , existing routes. if see controller not have route set in class version namespace , use pre-defined url prefix generate route version.
public void apply(applicationmodel application) { foreach (var controller in application.controllers) { var hasrouteattribute = controller.selectors.any(x => x.attributeroutemodel != null); if (hasrouteattribute) { continue; } var namespace = controller.controllertype.namespace.split('.'); var version = namespace.firstordefault(x => regex.ismatch(x, @"[v][\d*]")); if (string.isnullorempty(version)) { continue; } controller.selectors[0].attributeroutemodel = new attributeroutemodel() { template = string.format(urltemplate, apiprefix, version, controller.controllername) }; } }
i have code on github , link package on nuget well
Comments
Post a Comment