Accessing the query string in MVC 6 Web Api?

10,031

You can't have two [HttpGet]s with the same template in a single controller. I'm using asp.net5-beta7 and in my case it even throws the following exception:

Microsoft.AspNet.Mvc.AmbiguousActionException Multiple actions matched. The following actions matched route data and had all constraints satisfied:

The reason for this is that [From*] attributes are meant for binding, not routing.

The following code should work for you:

    [HttpGet]
    public dynamic Get([FromQuery] string withUser)
    {
        if (string.IsNullOrEmpty(withUser))
        {
            return new string[] { "project1", "project2" };
        }
        else
        {
            return "hello " + withUser;
        }
    }

Also consider using Microsoft.AspNet.Routing.IRouteBuilder.MapRoute() instead of attribute routing. It may give you more freedom defining the routes.

Share:
10,031
bootRom
Author by

bootRom

Updated on June 04, 2022

Comments

  • bootRom
    bootRom almost 2 years

    I am trying to add a Get() function in a MVC 6 (Asp .Net 5) Web Api to pass a configuration option as a query string. Here are the two functions that I already have:

    [HttpGet]
    public IEnumerable<Project> GetAll()
    {
        //This is called by http://localhost:53700/api/Project
    }
    
    [HttpGet("{id}")]
    public Project Get(int id)
    {
        //This is called by http://localhost:53700/api/Project/4
    }
    
    [HttpGet()]
    public dynamic Get([FromQuery] string withUser)
    {
        //This doesn't work with http://localhost:53700/api/Project?withUser=true
        //Call routes to first function 'public IEnumerable<Project> GetAll()
    }
    

    I've tried several different ways to configure the routing, but MVC 6 is light on documentation. What I really need is a way to pass some configuration options to the list of Projects for sorting, custom filtering etc.