• 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服务器

  • 相关阅读:
    python测试开发django186.使用 jquery 的 .val() 无法获取input框的输入值(已解决) 上海
    2022年第 10 期《python接口web自动化+测试开发》课程,2月13号开学! 上海
    python测试开发django185.bootstraptable 后端搜索功能实现(queryParams) 上海
    python测试开发django184.bootstraptable 前端分页搜索相关配置 上海
    python测试开发django181.自定义过滤器(除法取余) 上海
    python测试开发django180.dockercompose部署django+mysql环境 上海
    python测试开发django183.bootstrapformvalidation重置校验的方法 上海
    pytest文档79 内置 fixtures 之 cache 写入和读取缓存数据 上海
    python测试开发django182.jQuery重置form表单 上海
    golang interface用法
  • 原文地址:https://www.cnblogs.com/lhwpc/p/15189859.html
Copyright © 2020-2023  润新知