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

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

Patricia Arquette
Release: 2025-01-27 21:26:10
Original
332 people have browsed it

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

Sending Integer Arrays to ASP.NET Web APIs: A Practical Guide

This guide demonstrates how to effectively transmit an array of integers to an ASP.NET Web API action method. We'll address common pitfalls and provide the correct syntax for seamless data transfer.

Consider a Web API action method designed to accept an integer array:

<code class="language-csharp">public IEnumerable<category> GetCategories(int[] categoryIds)
{
    // Database retrieval logic for categories
}</code>
Copy after login

A naive approach might involve a comma-separated list in the URL query string:

<code>/Categories?categoryids=1,2,3,4</code>
Copy after login

This, however, fails because ASP.NET treats comma-separated values as distinct parameters. The solution lies in using the [FromUri] attribute and adjusting the URL structure.

Modify the action method to explicitly bind the parameter from the URI:

<code class="language-csharp">public IEnumerable<category> GetCategories([FromUri] int[] categoryIds)
{
    // Database retrieval logic for categories
}</code>
Copy after login

Now, the correct URL format, employing URL encoding, is:

<code>/Categories?categoryids=1&categoryids=2&categoryids=3&categoryids=4</code>
Copy after login

This method ensures proper deserialization of the integer array on the server-side. Each integer in the array is represented as a separate categoryids parameter.

This approach provides a clear and efficient method for passing integer arrays to your ASP.NET Web API, leveraging the [FromUri] attribute and correctly formatted URL encoding.

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

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template