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>
A naive approach might involve a comma-separated list in the URL query string:
<code>/Categories?categoryids=1,2,3,4</code>
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>
Now, the correct URL format, employing URL encoding, is:
<code>/Categories?categoryids=1&categoryids=2&categoryids=3&categoryids=4</code>
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!