首页 > c# > GET方法的角度发送字符串列表参数

GET方法的角度发送字符串列表参数 (Angular sending string list parameter by GET method)

问题

我有一个有角度的6项目。我正在向.Net Core 2.1 Web API发送请求。我正在发送如下的字符串水果列表。但是,我的数据仅作为一个项目来到c#"'apple', 'orange', 'banana'"。但是,我想要三个不同的字符串。我怎样才能做到这一点?请不要使用“POST”方法

角边

getFruitDetails() {
    let params = new HttpParams();
    params = params.append('fruitType', '35');
    params = params.append('fruits', JSON.stringify(['apple', 'orange', 'banana']));

    return this.http.get('https://localhost:5000/api/Fruit/GetFruitDetails', { params: params });
}

C#边

public GetFruitDetails([FromQuery] FruitModel fruitModel)
{...}

public class FruitModel
{
    public int FruitType { get; set; }
    public List<string> Fruits { get; set; }
}

解决方法

FromQuery属性将添加fruits=value从查询字符串匹配到列表Fruits的所有查询参数。

因此,将params组成

getFruitDetails() {
    let params = new HttpParams();
    params = params.append('fruitType', '35');
    params = params.append('fruits', 'apple');
    params = params.append('fruits', 'orange');
    params = params.append('fruits', 'banana');

    return this.http.get('https://localhost:5000/api/Fruit/GetFruitDetails', { params: params });
}

问题

I have an angular 6 project. And I'm sending my request to .Net Core 2.1 Web API. I'm sending string fruit list like below. But, my data coming to c# as only one item like "'apple', 'orange', 'banana'" . But, I want three different string. How can I achieve this? Please don't advice using "POST" method

Angular side

getFruitDetails() {
    let params = new HttpParams();
    params = params.append('fruitType', '35');
    params = params.append('fruits', JSON.stringify(['apple', 'orange', 'banana']));

    return this.http.get('https://localhost:5000/api/Fruit/GetFruitDetails', { params: params });
}

C# Side

public GetFruitDetails([FromQuery] FruitModel fruitModel)
{...}

public class FruitModel
{
    public int FruitType { get; set; }
    public List<string> Fruits { get; set; }
}

解决方法

The FromQuery attribute will add all query params that matching fruits=value from the querystring into the list Fruits.

Therefore, compose the params as

getFruitDetails() {
    let params = new HttpParams();
    params = params.append('fruitType', '35');
    params = params.append('fruits', 'apple');
    params = params.append('fruits', 'orange');
    params = params.append('fruits', 'banana');

    return this.http.get('https://localhost:5000/api/Fruit/GetFruitDetails', { params: params });
}
相似信息