1

I have a controller with a GET method as follows:

 [HttpGet]
 [Route("customer/{custId}")]
 public ActionResult GetCustomers([FromRoute]string custId, string prodId= "", string tagNo = "")
 {
 }

I want this to work like:

 /api/customer/123  -- where it returns the data for customer id =123
 /api/customer      -- where it returns all customers
 /api/customer?prodId=xyz  --where it returns data for productId=xyz
 /api/customer?tagNo=xyz123 

But currently, it only works in the following way:

 /api/customer/123?prodId=xyz

Is there a way I could do that in just one method

2 Answers 2

4

I presume you're getting a 404 Not Found when trying to hit /api/customer. You can make the parameter optional by adding a ? at the end of the parameter name.

So the method signature would look like this:

[HttpGet]
[Route("customer/{custId?}")]
public ActionResult GetCustomers([FromRoute]string custId, [FromQuery]string prodId= "", [FromQuery]string tagNo = "")
{}
Sign up to request clarification or add additional context in comments.

Comments

2

FromQuery attribbute may be helpful:

[HttpGet]
[Route("customer/{custId?}")]
public ActionResult GetCustomers(string custId, [FromQuery] string prodId = "", 
    [FromQuery] string tagNo = "")
{
}

This should work with every case.

1 Comment

Also a hint: If you want to make your endpoinds more RESTful, you should use plural forms in route (customers)

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.