Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Route instead of RoutePrefix at controller level in .net web api attribute routing

If I decorate this web api controller with the Route attribute I can hit the method

[Route("api/v{version}/bank-accounts")]
public class BankAccountsController : ApiController
{
    [HttpGet]
    public HttpResponseMessage GetBankAccounts()
    {
        //...
    }
}

But if I use RoutePrefix instead I can't make it work unless at the same time I use Route("")

[RoutePrefix("api/v{version}/bank-accounts")]
public class BankAccountsController : ApiController
{
    [HttpGet]
    [Route("")]
    public HttpResponseMessage GetBankAccounts()
    {
        //...
    }
}

Is this intended, or I'm messing things?

Thanks

like image 518
mitomed Avatar asked Nov 21 '13 08:11

mitomed


People also ask

What is difference between route and RoutePrefix?

Route prefixes are associated with routes by design in attribute routing. It is used to set a common prefix for an entire controller.

How do I set the default route in .NET Core Web API?

Right click your web project -> Select Properties -> Select the Debug tab on the left -> Then edit the 'Launch Url' field to set your own default launch url.

Which method is generally used for registering Web API routes?

Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

How do you override the prefix route?

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.


2 Answers

Right, this is an expected behavior... RoutePrefix attribute by itself doesn't add any routes to the route table where as Route attributes do...

like image 97
Kiran Avatar answered Sep 21 '22 13:09

Kiran


You are missing it... The route prefix, is just that, a prefix. You should move part of the path template to the route attribute. Like this.

[RoutePrefix("api/v{version}")]
public class BankAccountsController : ApiController
{
    [HttpGet]
    [Route("bank-accounts")]
    public HttpResponseMessage GetBankAccounts(string version)
    {
        //...
    }
}
like image 35
John C Avatar answered Sep 17 '22 13:09

John C