Yogi Bear
Yogi Bear

Reputation: 963

Angular to C# Http passing query parameters

I think the C# HttpGet TEMPLATE is what I am missing, but here’s the details. On the Angular front end:

let params = new HttpParams()
  .append('GDWarn', values[0].toString())
  .append('GDLimit', values[1].toString())
  .append('NDWarn', values[2].toString())
  .append('NDLimit', values[3].toString())
let url = `${this.url}/CalibrationModelFile/UpdateLimits/${this.networkID}/${constID}/{params}`

Here I assume this.http.get(url, … will do some magic to recognize HttpParams is a set of QUERY parameters. So the C# backend to receive the http request:

[HttpGet("CalibrationModelFile/UpdateLimits/{networkID:int}/{ConstituentID:int}/{values}")]
public async Task UpdateConstituentLimits(int networkID, int ConstituentID, [FromQuery] double[,] values)

I think the [FromQuery] may be right, but NOT enough. The {values] in the template probably should have something so we know it's QUERY PARMS?

Any thoughts?

Thanks in Advance, Yogi

Upvotes: 2

Views: 1398

Answers (1)

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

Sending an Array as Query Parameters

If you're trying to get a set of query params and route params like this:

.../UpdateLimits/networkID/ConstituentID?values=array

you should send a request as shown in the sample:

.../UpdateLimits/1/2?values=3.0&values=4.0&values=5.0

Query Parameters are not Part of a Route

Action's arguments in C# will be:

[HttpGet("CalibrationModelFile/UpdateLimits/{networkID:int}/{ConstituentID:int}")]
public async Task UpdateConstituentLimits(int networkID, int ConstituentID, [FromQuery] double[] values)

In the above sample {values} is removed from the route because QueryParam is not a part of a route. Also, it's better to decorate route parameters with [FromRoute] attribute.

2D Array as Query Parameters

Now, if the case is a 2D array as a query param, a simple solution is converting a 2D array into a string and parse the string in the C# action as following code:

.../UpdateLimits/1/2?values=GDWarn:4.1,GDLimit:3.7,NDWarn:6.3,NDLimit:4.8

and parsing query string in the resulted action will be like this:

    [HttpGet("{networkID:int}/{ConstituentID:int}")]
    public IEnumerable<WeatherForecast> Get([FromRoute]int networkID,
        [FromRoute]int ConstituentID, [FromQuery]string values)
    {
        // received string is: "GDWarn:4.1,GDLimit:3.7,NDWarn:6.3,NDLimit:4.8"
        var dict = new Dictionary<string, double>();
        foreach (var item in values.Split(','))
            dict.Add(item.Split(':')[0], Convert.ToDouble(item.Split(':')[1]));

        return (...)

    }

Upvotes: 1

Related Questions