Passing Integer Arrays to ASP.NET Web API Action Methods
This guide demonstrates how to effectively pass arrays of integers as parameters to your ASP.NET Web API action methods.
Method 1: Using the [FromUri]
Attribute
This approach utilizes the [FromUri]
attribute to retrieve the integer array from the URL's query string.
Within your action method, define a parameter to accept the integer array, decorated with [FromUri]
:
public IEnumerable GetCategories([FromUri] int[] categoryIds)
{
// Process the categoryIds array here
}
To send the array, structure your URL query string like this:
/Categories?categoryids=1&categoryids=2&categoryids=3
Each integer value is a separate parameter, separated by an ampersand (&).
Method 2: Using Comma-Separated Values
Alternatively, you can transmit the integer array using comma-separated values (CSV) in the query string. While not directly supported as an array, you can easily parse the CSV string within your action method:
public IEnumerable GetCategories(string categoryIds)
{
if (!string.IsNullOrEmpty(categoryIds))
{
int[] ids = categoryIds.Split(',').Select(int.Parse).ToArray();
// Process the 'ids' array here
}
}
The URL for this method would be:
/Categories?categoryIds=1,2,3,4
This approach simplifies the URL structure but requires additional parsing within the action method. Choose the method that best suits your needs and coding style. Remember to handle potential exceptions (e.g., FormatException
) during parsing if using the CSV method.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3