1

So I am familiar with how to write the default Get, Post, Put, Delete

//GET api/customer
public string Get(){}

//GET api/customer/id
public string Get(int id){}

//POST api/customer
 public void Post([FromBody]string value){}

//PUT api/customer/id
public void Put(int id, [FromBody]string value){}

//DELETE api/customer/id
 public void Delete(int id){}

But how would I write add another Get endpoint w/o having to create a whole new controller? I want to grab the customer's metadata? do I need to make any changes to the routeConfig? if so how would I do that? and then how would I use the new route in javascript?

//GET api/customer/GetMetaData
 public string GetMetaData(){
 }

1 Answer 1

1

You use the Attribute Route. This attribute was added in WebApi 20 and you can use it at Method level to define new route or more routes and the way you use it is like [Route("Url/route1/route1")]:

Using one of your examples above it will be like:

//GET api/customer/GetMetaData
[Route("api/customer/GetMetaData")]
public string Get2(){
      //your code goes here
}

If you will be declaring several Routes in your class then you can use RoutePrefix attribute like [RoutePrefix("url")] at class level. This will set a new base URL for all methods your in Controller class.

For example:

[RoutePrefix("api2/some")]
public class SomeController : ApiController
{
    // GET api2/some
    [Route("")]
    public IEnumerable<Some> Get() { ... }

    // GET api2/some/5 
    [Route("{id:int}")]
    public Some Get(int id) { ... } 

}

Note: In the example above I showed one example where Route allowed us to set type constraints as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! that was it. [Route("api/customer/GetMetaData")]. I was googling "multiple endpoints" when I should have been googling for route attributes. asp.net/web-api/overview/web-api-routing-and-actions/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.