0

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?

1
  • Sorry about posting a duplicate. I searched under "routing" and forgot to check "route" Commented May 31, 2016 at 5:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.