阅读 111

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 _users;
        public List Users 
        {
            get { return _users; }
        }


        public UserServer()
        {
            _users=new List(){ 
              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(new UserServer());
            services.AddGrpcClient(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 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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐