ASP.Net Core Web API调用Grpc服务,采用依赖注入客户端

1、新建ASP.Net Core Web API 应用程序

 2、修改launchSettings.json

{
  
  "profiles": {
    "WebApiService": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5007",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

3、引用上一篇的Grpc客户端程序集

 4、Nuget包下载

Grpc.Net.Client
Google.ProtoBuf

Grpc.Net.ClientFactory

5、新建User.cs

    public class User
    {
        public string Name { get; set; }

        public string Phone { get; set; }
    }

6、新建UserServer.cs

  public class UserServer
    {
        private List<User> _users;
        public List<User> Users 
        {
            get { return _users; }
        }


        public UserServer()
        {
            _users=new List<User>(){ 
              new User() {Name="qqq",Phone="1213" },
              new User() {Name="www",Phone="12345345" },
              new User() {Name="eee",Phone="5675765" },
              new User() {Name="rrr",Phone="54657" },
              new User() {Name="ttt",Phone="78698790" },
            };
        }

    }

7、修改Startup.cs

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApiService", Version = "v1" });
                c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
            });
            services.AddSingleton<UserServer>(new UserServer());
            services.AddGrpcClient<TestGrpc.TestGrpcClient>(options =>
            {
                options.Address = new Uri("http://localhost:5000");
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiService v1"));
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

8、新建MyApiController.cs

 [Route("api/[controller]/[action]")]
    [ApiController]
    public class MyApiController : ControllerBase
    {
        private readonly UserServer _userServer;
        private readonly TestGrpc.TestGrpcClient _testGrpcClient;

        public MyApiController(UserServer userServer, TestGrpc.TestGrpcClient testGrpcClient)
        {
            _userServer = userServer;
            _testGrpcClient = testGrpcClient;
        }

        [HttpGet]
        public IEnumerable<User> Get()
        {
            return _userServer.Users;;
        }

        [HttpPost]
        public User GetAll(string name)
        {
            return _userServer.Users.Find(_=>_.Name==name); ;
        }

        [HttpGet]
        public string GetGrpc()
        {
            string ret = string.Empty;

            //GrpcChannel _channel = GrpcChannel.ForAddress("http://localhost:5000");
            //TestGrpc.TestGrpcClient _testGrpcClient = new TestGrpc.TestGrpcClient(_channel);
            //var resp = _testGrpcClient.TestSay(new TestRequest { Name = "MyAspNetCoreMvc" });
            //ret = resp.Message;
            //_channel.Dispose();

            var resp = _testGrpcClient.TestSay(new TestRequest { Name = "MyAspNetCoreMvc" });
            ret = resp.Message;

            return ret;
        }
    }

9、依然调用Grpc系列文章中的建立的Grpc服务器

原文地址:https://www.cnblogs.com/lhwpc/p/15189859.html