Our company is developing an API for our products and we are thinking about using ASP.NET MVC. While designing our API, we decided to use calls like the one below for the user to request information from the API in XML format:
As you can see, multiple parameters are passed (i.e. artist
and api_key
). In ASP.NET MVC, artist
would be the controller
, getImages
the action, but how would I pass multiple parameters to the action?
Is this even possible using the format above?
Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:
MVC will auto-populate the parameters when given a URL like:
One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:
would be populated correctly with a URL like the following:
In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:
If you wanted to support a url like
you could add a route like:
and a method like the first example above.
You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:
That could be:
So if someone used the following route:
It would take them to the same place your example querystring did.
The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.
Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.
A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
Summary:
First you enable attribute routing
Then you can use attributes to define parameters and optionally data types