a blog for those who code

Wednesday 8 February 2017

How to set Default and Optional Route Values in Asp Net Web API

In this post we will be discussing about setting default and optional route values in Asp.Net Web API. Asp.Net Web API makes it really simple to define default values or optional values for a route whether its an attribute routing or centralized routing. Whenever you define any route in Asp.Net Web API, its always better to provide default values for the parameters used in the routes.


Default Route Values are the values that will be automatically be populated if the clients failed to pass them whereas you can make a URI parameter optional by adding a question to the route parameter. One thing to note that if a route parameter is defined as optional, you must define a default value for the method parameter.

Define Default Values


// In Centralized Routing
config.Routes.MapHttpRoute(
  name: "WebAPIDemo",
  routeTemplate: "{myController}/{value}",
  defaults: new { value = 10 }
);

// In Attribute Routing
[Route("myController/{id:int=10}")]
public HttpResponseMessage Get(int id) {}

Define Optional Values


// In Centralized Routing
config.Routes.MapHttpRoute(
  name: "WebAPIDemo",
  routeTemplate: "{myController}/{value}",
  defaults: new { param = RouteParameter.Optional }
);

// In Attribute Routing
[Route("myController/{id?}")]
public HttpResponseMessage Get(int? id=null) {}

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment