Search code examples
asp.netasp.net-mvcasp.net-mvc-routing

ASP.NET MVC Routing: Multiple parameter in URL


I'm trying to port a webservice from PHP to ASP.NET MVC. Which, of course, means I have to duplicate the existing API.

Presently, a call, in it's canonical form would be like:

http://example.com/book/search?title=hamlet&author=shakes

However, it also accepts an alternate form:

http://example.com/book/search/title/hamlet/author/shakes

There are about five different search criteria, all optional, and they can be given in any order.

How does one do that in ASP.NET MVC Routing?


Solution

  • You can try something like this.

    [Route("Book/search/{*criteria}")]
    public ActionResult Search(string criteria)
    {
        var knownCriterias = new Dictionary<string, string>()
        {
            {"author", ""},
            {"title",""},
            {"type",""}
        };
        if (!String.IsNullOrEmpty(criteria))
        {
    
            var criteriaArr = criteria.Split('/');
            for (var index = 0; index < criteriaArr.Length; index++)
            {
    
                var criteriaItem = criteriaArr[index];
                if (knownCriterias.ContainsKey(criteriaItem))
                {
                    if (criteriaArr.Length > (index + 1))
                        knownCriterias[criteriaItem] = criteriaArr[index + 1];
                }
            }
        }
        // Use knownCriterias dictionary now.
        return Content("Should return the search result here :)");
    }
    

    The last parameter prefixed with * is like a catch-all parameter which will store anything in the url after Book/search.

    So when you request yoursite.com/book/search/title/nice/author/jim , the default model binder will map the value "title/nice/author/jim" to the criteria parameter. You can call the Split method on that string to get an array of url segments. Then convert the values to a dictionary and use that for your search code.

    Basically the above code will read from the spilled array and set the value of knownCriteria dictionary items based on what you pass in your url.