Why
we need versioning in Api?
Once a Web API service is made
public, different client applications start using your Web API services.As the
business grows and requirements change, we may have to change the services as
well, but the changes to the services should be done in way that does not break
any existing client applications. This is when Web API versioning helps.
There are many approaches about
how should one implement the api versioning. My favorite is putting the
versioning in the Url path. It has following major benefits over other
approaches is that "you can change the entire relationship of entities in
future versions and still continue to support the old clients".
Step 1:- Create the visual studio
project (Select WebApi Project Template)
Step 2:- To Implement Api
Versioning you need to add following nuget
Install-Package
Microsoft.AspNet.WebApi.Versioning
Step 3:- Enable Api versioning
in Configuration class
1)
Remove
config.MapHttpAttributeRoutes(); from code because we implements in versioning.
2)
Add Following line of code before
route table:-
#region Enable Api
versioning
config.AddApiVersioning();
var
constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap = { ["apiVersion"] = typeof(ApiVersionRouteConstraint) }
};
config.MapHttpAttributeRoutes(constraintResolver);
#endregion
Notes:-[Make sure that this line of
code above route table created code otherwise versioning not work]
Step 4:- Create Controller
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/helloworld")]
public class HelloWorldController : ApiController
{
public string Get()
{
return "Hello World V1";
}
}
Step 5:- Run Program and type
http://localhost:{PortNumber}/api/v1.0/helloworld
Output:- "Hello World V1"
Step 6:- Copy above code in
same file and rename it
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/helloworld")]
public class HelloWorld2Controller : ApiController
{
public string Get()
{
return "Hello World V2";
}
Step
7:- Run Program and type http://localhost:{PortNumber}/api/v2.0/helloworld
Output:- "Hello World V2"
The full code is published in git hub repository. You can git pull and use it.
Hope you like it. Stay tuned for more..
Comments
Post a Comment