Home >Backend Development >C++ >How to Pass an Array of Integers to an ASP.NET Web API Action Method?

How to Pass an Array of Integers to an ASP.NET Web API Action Method?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-27 21:21:09354browse

How to Pass an Array of Integers to an ASP.NET Web API Action Method?

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]:

<code class="language-csharp">public IEnumerable<category> GetCategories([FromUri] int[] categoryIds)
{
    // Process the categoryIds array here
}</code>

To send the array, structure your URL query string like this:

<code>/Categories?categoryids=1&categoryids=2&categoryids=3</code>

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:

<code class="language-csharp">public IEnumerable<category> GetCategories(string categoryIds)
{
    if (!string.IsNullOrEmpty(categoryIds))
    {
        int[] ids = categoryIds.Split(',').Select(int.Parse).ToArray();
        // Process the 'ids' array here
    }
}</code>

The URL for this method would be:

<code>/Categories?categoryIds=1,2,3,4</code>

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.

The above is the detailed content of How to Pass an Array of Integers to an ASP.NET Web API Action Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn