0

Im trying to create a GET request that can handle few optional searching/filter params.

The request should look like:

https://localhost:99999/api/computers?ModelName=asus&RAM=2&ScreenSize=22

or

https://localhost:99999/api/computers?ModelName=asus&RAM=2

or

https://localhost:99999/api/computers?RAM=2&ScreenSize=22

or

https://localhost:99999/api/computers

The point is that it can have multiple optional params like: ModelName, RAM, ScreenSize or just RAM, ScreenSize or ModelName, RAM or empty.

The conroller looks like:

    [HttpGet]
    public IHttpActionResult GetComupters(string ModelName, int? RAM, int? ScreenSize)
    {
        return Ok();
    }

How should i build the RouteTemplate for this type of search\filtering?

Thanks!!!

1 Answer 1

1

Just enough a default route. You don't need anything extra for this. You can add attribute route.

 [HttpGet("~/api/computers")]
  public IHttpActionResult GetComupters(string ModelName, int? RAM, int? ScreenSize)

It was tested in net core and works properly.

But if you use old net version your register routes can be looking like this

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
 
    routes.MapMvcAttributeRoutes();
 
    routes.MapRoute(
        name: “Default”,
        url: “api/{controller}/{action}/{id}”,
        defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
    );
}
Sign up to request clarification or add additional context in comments.

10 Comments

I tried it but im getting 405 each time I try to lunch a request with less than those 3 params. getting 200 only with that : localhost:44390/api/…
@DavidAxelrod I tested it in net core using Postman and everything works properly. What mvc version and net version are you using?
The 405 Method Not Allowed is usually gives error if you use post instead of get. How do you call this action? pls post your view
Hi im using the latest version of MVC github.com/davidax0204/WebApiCRUD---Computers Could you maybe please take a look maybe a did something wrong
|

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.