Home >Backend Development >C++ >How to Route Multiple Parameters in ASP.NET MVC?
Detailed explanation of multi-parameter routing in ASP.NET MVC
When designing a RESTful API based on ASP.NET MVC, it is often necessary to pass multiple parameters to the controller action method. This article will explore how to deal with this situation and explain in detail the methods available.
Use query string to pass parameters
By default, MVC automatically maps query string parameters to action method parameters. Consider these how-tos:
<code class="language-csharp">public ActionResult GetImages(string artist, string apiKey)</code>
An HTTP request like this:
<code>http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&api_key=my_key</code>
The artist and apiKey parameters will be populated when calling the GetImages operation.
Special case of "id" parameter
A parameter named "id" can be included in the URL path instead of the query string. For example, the following:
<code class="language-csharp">public ActionResult GetImages(string id, string apiKey)</code>
Can be called using the following URL:
<code>http://ws.audioscrobbler.com/2.0/Artist/GetImages/cher?api_key=my_key</code>
Custom routing rules
For more complex cases, MVC provides the flexibility to customize routing rules to find actions. In the global.asax file, edit the routes.MapRoute method, which specifies the default routing mode.
Example: Custom routing with specific parameters
To handle URLs like this:
<code>http://ws.audioscrobbler.com/2.0/Artist/GetImages/cher/my_key</code>
The following routes can be added:
<code class="language-csharp">routes.MapRoute( "ArtistImages", "{controller}/{action}/{artistName}/{apiKey}", new { controller = "Artist", action = "GetImages", artistName = "", apiKey = "" } );</code>
With this custom route, the GetImages operation will be called and the artistName and apiKey parameters will be populated from the URL segment.
The above is the detailed content of How to Route Multiple Parameters in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!