Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# API HTTP Dynamic Parameters

Tags:

c#

asp.net

Hey I would like to achieve something that with dynamic parameters.

For example I have this Controller Action:

[HttpGet]
public async Task TestParam(string firtname, string lastname, string persnr)
{
    Console.WriteLine("Firstname: " + firtname);
    Console.WriteLine("Lastname: " + lastname);
    Console.WriteLine("Persnr: " + persnr);
}        

Is it possible that my request can look like this:

Url Firstname Lastname Persnr
URL/?firtname=Test&lastname=Test&persnr=123 Test Test 123
URL/?firtname=Test&persnr=123 Test 123
URL/?lastname=Test&persnr=123 Test 123
URL/?persnr=123 123

So basically that I don't have to write all parameters?

Because if I make them optional with

TestParam(string firtname = "", string lastname = "", string persnr = "")

I have to write the url like that

URL/?firtname=&lastname=&persnr=123

to only see the persnr.

What is the best way to achieve this?

like image 511
Timebreaker900 Avatar asked May 16 '26 10:05

Timebreaker900


1 Answers

You can create a model class for your query parameters like this:

public class TestQuery
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Persnr { get; set; }
}

Then you can replace your TestParam signature like this:

public async Task TestParam([FromUri]TestQuery queryParams)

For more information please check this MSDN article.

like image 83
Peter Csala Avatar answered May 18 '26 01:05

Peter Csala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!