如何在 API 控制器中调用 POST 操作?

问题描述 投票:0回答:1

我不知道如何将值字符串或模型发送到 HttpPost-action

我想向 API 中的 HttpPost-action 发送一个值。 他到达了 HttpPost 操作。但参数名称的值为NULL。 我做错了什么?

例如“name”的值=“Netherlands”。

public async Task<long> UpdateCountry(string name)
{
    string url = $"{myApi}/Address/UpdateCountry";
    var model = JsonConvert.SerializeObject(new KeyValuePair<string, string>("name", name));
    long id = await Post(url, model);

    return id;
}

该过程在 BaseClass 中开始...在 Post 函数中。

protected async Task<dynamic> Post(string url, string data)
{
    var client = new HttpClient();

    var httpContent = new StringContent(data);
    HttpResponseMessage responseMessage = await client.PostAsync(url, httpContent);

    var result = await responseMessage.Content.ReadAsStringAsync();

    return JsonConvert.DeserializeObject<dynamic>(result);
}

API中参数名称的值为NULL。

[HttpPost("UpdateCountry")]
    public async Task<long> UpdateCountry(string name)
    {
        var countryId = _countryService.GetIdByName(name);

        if (countryId == null)
        {
            var dto = new CountryDto() { Name = name };
            ....
            countryId = await _countryService.Insert(dto);
        }
        else
{
dto.Name = name;
            countryId = await _countryService.Update(dto);
}
        return countryId.Value;
    }

c# asp.net-web-api dotnet-httpclient
1个回答
0
投票

在客户端

public async Task<long> UpdateCountry(string name)
{
    string url = $"{myApi}/Address/UpdateCountry";
    var json = JsonConvert.SerializeObject(name);
    long id = await Post(url, json, "text/json"); // or "application/json" when  you use a model.

    return id;
}

...和基类

protected async Task<dynamic> Post(string url, string data, string mediaType)
{
    var client = new HttpClient();
    var content = new StringContent(data, Encoding.UTF8, mediaType);
    var response = await client.PostAsync(url, content);
    if (response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<dynamic>(result);
    }

    return null;
}

...以及 API 中

    [HttpPost("UpdateCountry")]
    public async Task<long> UpdateCountry([FromBody] string name)
    {
        var countryId = _countryService.GetIdByName(name);

        if (!countryId.HasValue)
        {
            var dto = new CountryDto() { Name = name };
            ....
            countryId = await _countryService.Insert(dto);
        }
        else
        {
            ....
            dto.Name = name;
            countryId = await _countryService.Update(dto);
        }

        return countryId.Value;
    }
© www.soinside.com 2019 - 2024. All rights reserved.