Home > front end >  ASP.NET MVC GET request with multiple optional filter query params
ASP.NET MVC GET request with multiple optional filter query params

Time:09-21

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!!!

CodePudding user response:

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 }
    );
}
  • Related