1

I have a web API method, which takes json request object

{
    "FundCodes":["0DFOY"],
    "FromDate":"2021-04-01",
    "ToDate":"2021-05-01"
}

As this api retrieves data, I think the web API needs to be a GET.

However, if I do that, how do I pass above in a query string?

I know that HTTP GET does have a body and I can put the parameter in, but I think lots of people are against the idea of using a body. So how do I put this into query string?

I used this site to urlencode the parameter, but seems my API call doesn't recognise the passed parameter. https://onlinejsontools.com/url-encode-json

So is there a bit more official way on web API design for this? Maybe I should use POST other than GET?

2
  • how about convert it to an object and take a look on this ? Commented Aug 31, 2021 at 17:08
  • Too much hassle, if I do that, better just use post I think Commented Aug 31, 2021 at 17:45

1 Answer 1

4

The first way, you can pass query string like below:https://localhost:portNumber/WeatherForecast?fundcodes=aaa&fundcodes=bbb&fromDate=2021-04-01&toDate=2021-05-01.

Model:

public class TestModel
{
    public string[] FundCodes { get; set; }
    public string FromDate { get; set; }
    public string ToDate { get; set; }
}

Controller:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]

    public IActionResult Get([FromQuery]TestModel model)
    {
        return Ok(model);
    }
}

The result you will get:

enter image description here

The second way, you can pass query string in browser like below:https://localhost:portNumber/WeatherForecast?json={"FundCodes":["0DFOY"],"FromDate":"2021-04-01","ToDate":"2021-05-01"}. The browser will dynamic encode this url and pass to backend.

If you want to send encoded url manually, the url should be: https://localhost:portNumber/WeatherForecast?json={%22FundCodes%22:[%220DFOY%22],%22FromDate%22:%222021-04-01%22,%22ToDate%22:%222021-05-01%22} or https://localhost:portNumber/WeatherForecast?json=%7B%22FundCodes%22%3A%5B%220DFOY%22%5D%2C%22FromDate%22%3A%222021-04-01%22%2C%22ToDate%22%3A%222021-05-01%22%7D.

Controller:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public IActionResult Get([FromQuery]string json)
    {
        var model = System.Text.Json.JsonSerializer.Deserialize<TestModel>(json);      
        return Ok(model);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.