ASP.NET Web API Contract Versioning -
we achieve version based api using content negotiation in accept header.
we able achieve controller & api methods inheritance , extending default http selector.
controller inheritance achieved using following sample code,
public abstract class abstractbasecontroller : apicontroller { // common methods api } public abstract class abstractstudentcontroller : abstractbasecontroller { // common methods student related api'sample public abstract post(student student); public abstract patch(student student); } public class studentv1controller : abstractstudentcontroller { public override post([frombody]student student) // student should instance of studentv1 json { // do: insert v1 student } public override patch([frombody]student student) // student should instance of studentv1 json { // do: patch v1 student } } public class studentv2controller : abstractstudentcontroller { // public override post([frombody]student student) // student should instance of studentv2 json { // do: insert v2 student } } public abstract class student { public string firstname { get; set; } public string lastname { get; set; } } public class studentv1 : student { } public class studentv2 : student { public string email { get; set; } }
we have created above architecture less code change in version, if version 1 has 10 api methods , there change in 1 api method should available in version 2 code without modifying other 9(they inherited version 1).
now, main problem facing in contract versioning cannot instantiate instance of abstract student. when posting json api version 1 instance of studentv1 should passed in methods , same in version 2.
is there way achieve this?
thanks in advance!!
based on pasted code make abstractstudentcontroller generic. because apis declare abstract must implemented in every api version, , can define type generic. hope i'm not missing description, because patch missing implementation in studentv2controller, declared abstract. wanted derive studentv2controller studentv1controller?
public abstract class abstractbasecontroller : apicontroller { // common methods api } public abstract class abstractstudentcontroller<studenttype> : abstractbasecontroller { // common methods student related api'sample public abstract post(studenttype student); public abstract patch(studenttype student); } public class studentv1controller : abstractstudentcontroller<studentv1> { public override post([frombody]studentv1 student) // student should instance of studentv1 json { // do: insert v1 student } public override patch([frombody]studentv1 student) // student should instance of studentv1 json { // do: patch v1 student } } public class studentv2controller : abstractstudentcontroller<studentv2> { // public override post([frombody]studentv2 student) // student should instance of studentv2 json { // do: insert v2 student } }
Comments
Post a Comment