1

I am trying to create a web API. As part of it I want to create a Get method which any accept any number of variable of a particular type.

public class MyController : ControllerBase
    {
        [HttpGet]
        public int[] Get(int[] ids)
        {

            for(int i = 0; i < ids.Length; i++)
            {
                ids[i] = ids[i] * 100;
            }

            return ids;
        }
    }

When I try to make a get request from postman using

https://localhost:44363/api/executionstatus?ids=1&ids=2&ids=3

I get an error

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|39f5d965-4240af31edd27f50.","errors":{"$":["The JSON value could not be converted to System.Int32[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."]}}

I have also tried with

https://localhost:44363/api/executionstatus?ids=1,2,3

but it is also resulting in the same error. What is the correct way to pass/handle multiple parameters from a get request?

1

2 Answers 2

2

I think if you explicitly mention you want to read the variable from the query string, it will work fine in the method you are describing:

//.net Core
public int[] Get([FromQuery]int[] ids)

//.net Framework
public int[] Get([FromUri]int[] ids)

The call:

https://localhost:44363/api/executionstatus?ids=1&ids=2&ids=3
Sign up to request clarification or add additional context in comments.

8 Comments

Can you try the object wrapper? Because that's how it's normally done. It allows a bit more freedom and flexibility for "complex" types. If it doesn't work I must have a typo somewhere.
Btw, I'll try to spinup a quick project to test the first method
@cvg: Cool, I hope it's sufficient for your case. I am now struggling myself on how to get that first one working XD
@cvg: I think I got it - but I am using .net core. Behavior is similar, but not identical
thanks @Stefan. I'm using .net core. using object wrapper I don't get error msgs. but the ids of data object being passed to the Get method is null
|
1

Maybe you could try with string parameter

[HttpGet]
public int[] Get(string ids)
{
    var intIds = ids.Split(',').Select(int.Parse).ToList();
    for(int i = 0; i < intIds.Length; i++)
    {
        intIds[i] = intIds[i] * 100;
    }
    return intIds;
}

and call your api like this

https://localhost:44363/api/executionstatus?ids=1,2,3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.