Routing is how Web API matches a URI to an action
Web API used convention-based routing
https://github.com/api2/github/iamchamith/BestPractices/blob/master/Test.ts
github is must
Web API used convention-based routing
https://github.com/api2/github/iamchamith/BestPractices/blob/master/Test.ts
[RoutePrefix("api2")] public class RoutingExampleController : ApiController { [Route("github/{user}/{repo}/blob/master/{file}")] public string GetFile(string user,string repo,string file) { return $"{user}-> {repo}->{file}"; } }
github is must
Route Constraints
[Route("user/{id:int}")] public string GetUser(int id) { return "Chamith " + id; }
Constraint | Description | Example |
---|---|---|
alpha | Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) | {x:alpha} |
bool | Matches a Boolean value. | {x:bool} |
datetime | Matches a DateTime value. | {x:datetime} |
decimal | Matches a decimal value. | {x:decimal} |
double | Matches a 64-bit floating-point value. | {x:double} |
float | Matches a 32-bit floating-point value. | {x:float} |
guid | Matches a GUID value. | {x:guid} |
int | Matches a 32-bit integer value. | {x:int} |
length | Matches a string with the specified length or within a specified range of lengths. | {x:length(6)} {x:length(1,20)} |
long | Matches a 64-bit integer value. | {x:long} |
max | Matches an integer with a maximum value. | {x:max(10)} |
maxlength | Matches a string with a maximum length. | {x:maxlength(10)} |
min | Matches an integer with a minimum value. | {x:min(10)} |
minlength | Matches a string with a minimum length. | {x:minlength(10)} |
range | Matches an integer within a range of values. | {x:range(10,50)} |
regex | Matches a regular expression. | {x:regex(^\d{3}-\d{3}-\d{4}$)} |
Optional URI Parameters and Default Values
Default parameter
public class BooksController : ApiController
{
[Route("api/books/locale/{lcid:int?}")]
public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... }
}
Url parameter
public class BooksController : ApiController
{
[Route("api/books/locale/{lcid:int=1033}")]
public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }
}
Init routing in application startup
inside Globle.asax
inside Globle.asax
protected void Application_Start() { RouteConfig.RegisterRoutes(RouteTable.Routes); }
Using router table
public static class WebApiConfig { public static void Register(HttpConfiguration config) {
// Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );}
}
No comments:
Post a Comment