Now we are going
to discuss about url rewriting using web API's . According to new
release of Web API2 , they implemented new type of url rewritng called
as 'attribute routing' which uses attribute to define routes.
Attribute routing gives you more control over URLs. Using this you
can easily creates urls that defines your resource hierarchic
Before
attribute routing Web-APIs use convention-base routing which is not
able to support all kinds of url structure for example the below type
of urls
/customers/1/orders
This type of
urls which is difficult to create using convention-base routing
But it is very
easy to create with attribute routing you can simple give the
structure as attributes like below
[
Route
(
"customers/{customerId}/orders"
)]
public
IEnumerable
<
Order
>
GetOrdersByCustomer
(
int
customerId) { ... }
For
enabling the attribute routing need to add the following code ton
WebApiConfig
class which is fount in App_start folder
public
static
class
WebApiConfig
{
public
static
void
Register(HttpConfiguration
config)
{
config.Routes.MapHttpRoute(
name:
"DefaultApi",
routeTemplate:
"api/{controller}/{id}",
defaults:
new
{ id = RouteParameter.Optional
}
);
}
}
and in your
controller add the Route attributes
public
class
OrdersController
:
Controller
{
[
Route
(
"customers/{customerId}/orders"
)]
[
HttpGet
]
public
IEnumerable
<
Order
>
FindOrdersByCustomer
(
int
customerId) { ... }
}
Note:- if
Route
trhrows
exception , then you need to install new web api pakages for mvc
Install-Package
AttributeRouting
(for
MVC)
Optional Parameter
We can also add optional parameter to the attribute routing . For that purpose we only have to do is
just add a question mark to the routing parameter which is optional please refer the example given below
[Route("search/{KeyId?}/{Keyword?}/{LocationID?}/{Location?}")]
We can also add optional parameter to the attribute routing . For that purpose we only have to do is
just add a question mark to the routing parameter which is optional please refer the example given below
[Route("search/{KeyId?}/{Keyword?}/{LocationID?}/{Location?}")]
public
ActionResult
search(string
KeyId, string
Keyword, string
LocationID, string
Location)
Please leave your comment ,It will be help full to improve my Blog
nice one....
ReplyDeleteGlad to know that it helped you.
DeleteVery good article.
ReplyDeleteThanks for your valuable feed back.
Delete