【问题标题】:how to return list<model> in grpc如何在 grpc 中返回 list<model>
【发布时间】:2020-09-18 12:09:22
【问题描述】:

我想在 grpc.project 中向客户端返回 Person 模型列表是 asp.net 核心

person.proto 代码是:

    syntax = "proto3";

option csharp_namespace = "GrpcService1";


service People {
  rpc GetPeople (RequestModel) returns (ReplyModel);
}

message RequestModel {
}

message ReplyModel {
  repeated Person person= 1;
}

message Person {
  int32 id = 1;
  string firstName=2;
  string lastName=3;
  int32 age=4;
}

PeopleService.cs 代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.Extensions.Logging;

namespace GrpcService1
{
    public class PeopleService:People.PeopleBase
    {
        private readonly ILogger<GreeterService> _logger;
        public PeopleService(ILogger<GreeterService> logger)
        {
            _logger = logger;
        }

        public override async Task<ReplyModel> GetPeople(RequestModel request, ServerCallContext context)
        {
            List<Person> people = new List<Person>() {
                new Person() { Id=1,FirstName="david",LastName="totti",Age=31},
                new Person() { Id=2,FirstName="lebron",LastName="maldini",Age=32},
                new Person() { Id=3,FirstName="leo",LastName="zidan",Age=33},
                new Person() { Id=4,FirstName="bob",LastName="messi",Age=34},
                new Person() { Id=5,FirstName="alex",LastName="ronaldo",Age=35},
                new Person() { Id=6,FirstName="frank",LastName="fabregas",Age=36}
            };
            ReplyModel replyModel = new ReplyModel();
            replyModel.Person = people;  //this line is error : Property or indexer 'ReplyModel.Person' cannot be assigned to --it is read only    
            return replyModel;
        }

    }
}

和客户端项目调用grpc服务器:

var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new People.PeopleClient(channel);
var result= client.GetPeople(new RequestModel(), new Grpc.Core.Metadata());

这适用于一个模型,但是当我想要返回模型列表时我不能。如何将列表发送到客户项目? 感谢您阅读我的问题

【问题讨论】:

    标签: c# asp.net-core grpc


    【解决方案1】:

    将错误行 (replyModel.Person = people) 更改为此代码

    replyModel.Person.AddRange(people);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-07
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多