Sometimes we need to pass data between web pages to share information in the form of variables or parameters. We can do this by using a “QueryString” of “Request” property in Asp.Net. QueryString is a part of the URL shown in the Address bar of a browser.
Step1: Create a Blank Solution called WebAPI-Multiple-Objects as shown below. Add a new class library project (Model) into it and create two classes named Product, Supplier. Now, on the API controller side, you will get your complex types as shown below.
Just add two request parameters, and give the correct path. Send that as a POST with the JSON data in the request body, not in the URL, and specify a content type of application/json .
Query parameters are passed after the URL string by appending a question mark followed by the parameter name , then equal to (“=”) sign and then the parameter value. Multiple parameters are separated by “&” symbol.
You also can use this:
// GET api/user/firstname/lastname/address
[HttpGet("{firstName}/{lastName}/{address}")]
public string GetQuery(string id, string firstName, string lastName, string address)
{
return $"{firstName}:{lastName}:{address}";
}
Note: Please refer to the answers from metalheart
and Mark Hughes
for a possibly better approach.
Why not using just one controller action?
public string Get(int? id, string firstName, string lastName, string address)
{
if (id.HasValue)
GetById(id);
else if (string.IsNullOrEmpty(address))
GetByName(firstName, lastName);
else
GetByNameAddress(firstName, lastName, address);
}
Another option is to use attribute routing, but then you'd need to have a different URL format:
//api/person/byId?id=1
[HttpGet("byId")]
public string Get(int id)
{
}
//api/person/byName?firstName=a&lastName=b
[HttpGet("byName")]
public string Get(string firstName, string lastName, string address)
{
}
To parse the search parameters from the URL, you need to annotate the controller method parameters with [FromQuery]
, for example:
[Route("api/person")]
public class PersonController : Controller
{
[HttpGet]
public string GetById([FromQuery]int id)
{
}
[HttpGet]
public string GetByName([FromQuery]string firstName, [FromQuery]string lastName)
{
}
[HttpGet]
public string GetByNameAndAddress([FromQuery]string firstName, [FromQuery]string lastName, [FromQuery]string address)
{
}
}
I would suggest to use a separate dto object as an argument:
[Route("api/[controller]")]
public class PersonController : Controller
{
public string Get([FromQuery] GetPersonQueryObject request)
{
// Your code goes here
}
}
public class GetPersonQueryObject
{
public int? Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
}
Dotnet will map the fields to your object.
This will make it a lot easier to pass through your parameters and will result in much clearer code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With