Skip to main content
 首页 » 编程设计

c#之如何将 IListMyObject> 作为参数传递给 Web API 中的 POST 方法

2024年04月18日37tintown

在我的项目中,我有一个名为 Project 的模型类,我的 REST 服务中有一个 POST 方法,它是用 Web API 开发的,我想接收一个 Project 列表,但我总是调用这个方法,即 IList参数为空。我需要做什么才能将列表作为参数传递?

那是我的 Controller :

[IdentityBasicAuthentication] 
[Authorize] 
[RoutePrefix("project")] 
public class ProjectController : ApiController 
{ 
    [HttpPost] 
    [Route("listafavoritos")] 
    public IList<PROSPERI_EpmFast.Core.Modelo.POCO.Project> ListaFavoritos([FromBody] List<PROSPERI_EpmFast.Core.Modelo.POCO.Project> projetos) 
    { 
         //execute the actions 
    } 
} 

这是我的服务电话:

    public virtual async Task<IList<Project>> ListaProjetosFavoritos(IList<Project> projetosFavoritos) 
    { 
 
 
       var url = "http://myserviceurl/project/listafavoritos"; 
 
 
        _client.DefaultRequestHeaders.Authorization = authentication; 
 
 
        foreach (Project projetoLimpar in projetosFavoritos) 
        { 
            projetoLimpar.Tasks = null; 
            projetoLimpar.Team = null; 
            projetoLimpar.Cost = null; 
            projetoLimpar.Schedule = null; 
        } 
 
        var uri = new Uri(string.Format(url, string.Empty)); 
        var json = JsonConvert.SerializeObject(projetosFavoritos, this._microsoftDateFormatSettings); 
        var contentEnvio = new StringContent(json, Encoding.UTF8, "application/json"); 
 
        _client.Timeout = new TimeSpan(0, 5, 0); 
        var response = await _client.PostAsync(uri, contentEnvio); 
 
        if (response.IsSuccessStatusCode) 
        { 
            var content = await response.Content.ReadAsStringAsync(); 
            return JsonConvert.DeserializeObject<IList<Project>>(content, this._microsoftDateFormatSettings); 
        } 
        return null; 
    } 

请您参考如下方法:

将参数转换为数组

[HttpPost] 
[Route("listafavoritos")] 
public IList<Project> ListaFavoritos([FromBody]Project[] projetos) { ... } 

并在发送数据时将数据转换为数组

//.... 
 
var payload = projetosFavoritos.ToArray(); 
var json = JsonConvert.SerializeObject(payload, this._microsoftDateFormatSettings); 
var contentEnvio = new StringContent(json, Encoding.UTF8, "application/json"); 
 
_client.Timeout = new TimeSpan(0, 5, 0); 
var response = await _client.PostAsync(uri, contentEnvio); 
 
//....