I was wondering that if we use RoutePrefix
attribute in our web api controller with a different name from controller's actual name. So would it work or not?
As far as i did
[RouterPrefix("quotation")]
public class SaleOrderController : ApiController { ... }
if we define RoutePrefix
like above we can't access it via /quotation
but we can access it using saleorder
.
So what is RoutePrefix
for or am i doing something wrong ?
Annotates a controller with a route prefix that applies to all actions within the controller. As you can see, the description for Route mentions exposing the action(s), but RoutePrefix does not.
We can override the RoutePrefix on a method, using the tilde(~) sign. We can easily define parameterized templates in the attribute based routing. We can have parameters defined in-between the API request URLs.
Once a matching route is found, Web API selects the controller and the action: To find the controller, Web API adds "Controller" to the value of the {controller} variable. To find the action, Web API looks at the HTTP verb, and then looks for an action whose name begins with that HTTP verb name.
Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System.
To use default route use Route("")
[RoutePrefix("quotation")]
public class SaleOrderController : ApiController {
//GET quotation
[Route("")]
[HttpGet]
public IHttpActionResult GetAll() { ... }
}
Source: Attribute Routing in ASP.NET Web API 2 : Route Prefix
In order for it to work, you need to call the code below inside your WebApiConfig.Register()
method:
config.MapHttpAttributeRoutes();
So your RoutePrefix
works as exptected:
[RoutePrefix("quotation")]
public class SaleOrderController : ApiController
{
[Route("example")]
[HttpGet]
public IHttpActionResult Example()
{
return Ok();
}
[Route("another")]
[HttpGet]
public IHttpActionResult Another()
{
return Ok();
}
}
So your could access your apis like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With