Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route Prefix VS Controller Name ( Web api )

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 ?

like image 988
Ahsan Attari Avatar asked Jan 25 '17 13:01

Ahsan Attari


People also ask

What is the difference between route and route prefix?

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.

How do you override a route prefix?

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.

How do I find my controller name in Web API?

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.

What are controllers in Web API?

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.


2 Answers

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

like image 141
Nkosi Avatar answered Nov 15 '22 00:11

Nkosi


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:

  • quotation/example
  • quotation/another
like image 25
Alisson Reinaldo Silva Avatar answered Nov 15 '22 00:11

Alisson Reinaldo Silva