ThisQRequiresASpecialist
ThisQRequiresASpecialist

Reputation: 1104

Get URL Query parameter in an API call C#

I've been doing some research on how to get query string parameters from a URL in C# through an API call and I could not find any relevant information on this. I found a bunch of sources on how to do it in PHP but that is not what I'm using.

I also don't know if I have to set up endpoints to accept the query string parameters as part of a call but I believe I do.

All of my Restful API currently works on URL paths so everything that I want to parse through to my backend is separated with a / and I don't want that. I would like to parse all information for processing through query strings and parse only specific path locations using /.

This is how my endpoints are currently set up.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "api/v1/{controller}/{id?}/{id1?}/{id2?}/{id3?}/{id4?}/{id5?}/{id6?}");
});

This is one of my API calls

[HttpGet("/api/v1/Templates/{customerId}")]
public List<string> GetTemplates(string customerId)
{
    return templatesService.GetTemplates(customerId);
}

I would like to parse my customer ID as http://localhost:0000/api/v1?customerId=1

Example with extra parameters:

[HttpPost("/api/v1/Templates/{customerId}/{templateName}/{singleOptions}/{multiOptions}")]
public string GetReplacedTemplate(string customerId, string templateName, string singleOptions, string multiOptions)
{
    return templatesService.GetReplacedTempalte(customerId, templateName, singleOptions, multiOptions);
}

So here I have 2 extra parameters which are SingleOptions and MultiOptions. Main controller is Templates.

I think even TemplateName should be parse as a Query as I feel like its extra param too.

This is not a problem that is required to solve as using / to separate each parameter works fine but I really want to know how to parse query strings as well.

Upvotes: 2

Views: 21402

Answers (1)

ThisQRequiresASpecialist
ThisQRequiresASpecialist

Reputation: 1104

I usually dont answer my own Questions but here it is for others to view.

To take Query string parameters in C# through an API call is actually easy.

Using the [FromQuery] DataBinding on your parameter will allow you to take what ever you parse it :)

[HttpGet("/api/v1/Templates")]
public string GetTemplatesQuery([FromQuery] string customerId)
{
    return customerId;
}

Upvotes: 8

Related Questions