rul3s
rul3s

Reputation: 342

How to read and iterate over HTTP GET parameters?

I'm doing a simple backend with .Net Core that reads data from GET and POST, but I'm not finding how to read GET params neither POST. I have this, a simple Controller:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    private readonly ILogger<TestController> _logger;

    public TestController(ILogger<TestController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public string Get()
    {

        return "Test GET OK";
    }

    [HttpPost]
    public string Post()
    {
        return "Test POST OK";
    }
}

Client, a simple windows forms with net framework 4.6, is using HttpClient to sent http get request:

public async Task<string> GetAsyncHttpClient(string uri)
{
    string responseBody = "";
    try
    {
        UriBuilder builder = new UriBuilder(uri);
        builder.Query = "name=testName";

        HttpResponseMessage response = await client.GetAsync(builder.Uri);
        response.EnsureSuccessStatusCode();
        responseBody = await response.Content.ReadAsStringAsync();
        // Above three lines can be replaced with new helper method below
        // string responseBody = await client.GetStringAsync(uri);
    }
    catch (Exception e)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ", e.Message);
        responseBody = "Error with GET operation, exception:\n" + e.ToString();
    }

    return responseBody;
}

And generated URL is like this:

http://localhost:5915/test?name=testName

Trust me that I've searched a lot and I didn't find how to read and iterate over GET params. How should I do it?

Thanks!

Upvotes: 1

Views: 2306

Answers (2)

lillcoder
lillcoder

Reputation: 23

I don't know exactly what you mean but if you just want to make a post or get request then you do it in your client like this:

using (var client = new HttpClient())
{
    try
    {
        HttpResponseMessage response =
            await client.PostAsync("https://localhost:YOURPORT/Test?username=test", YOURCONTENT);
        var cont = await response.Content.ReadAsStringAsync();
        Console.WriteLine(cont);
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
            
    Console.ReadKey();
}

make sure you are using http or https accordingly you have to adjust the url as well

if you mean Query Params you can access them by adding this to the API:

[HttpPost]
public void Post([FromQuery] string username){
//do something
}

Upvotes: -1

ProgrammingLlama
ProgrammingLlama

Reputation: 38795

Normally you would just add a parameter to your method:

[HttpGet]
public string Get(string name)

You can be explicit that it's a query string parameter like this:

[HttpGet]
public string Get([FromQuery]string name)

As for iterating the parameters, you'll have to use Request.Query:

foreach (KeyValuePair<string, StringValues> entry in Request.Query)
{
    string key = entry.Key;
    foreach (string value in entry.Value)
    {
        System.Diagnostics.Debug.WriteLine($"{key}={value}");
    }
}

You'll need to add a using Microsoft.Extensions.Primitives; for the StringValues. The reason why it's StringValues is because you could have a URL like this: https://www.example.com/test?name=Brian&name=Jennifer, so you would end up with two values in the Query collection entry for "name".

Upvotes: 4

Related Questions