zoukankan      html  css  js  c++  java
  • Asp.Net Core Web MVC 调用Grpc,采用依赖注入

    1、新建Asp.net Core Web Mvc项目

     2、Nuget包下载安装

    Grpc.Net.Client
    Google.ProtoBuf
    Grpc.Tools

    3、新建Protos文件夹,复制之前文章Grpc服务器的greet.proto文件

    syntax = "proto3";
    
    option csharp_namespace = "MyGrpcWeb";
    
    package MyGrpc;
    
    // The greeting service definition.
    service TestGrpc {
      // Sends a greeting
      rpc TestSay (TestRequest) returns (TestReply);
    
      rpc StreamingFromServer(ExampleRequest) returns (stream ExampleResponse);
    
      rpc StreamingFromClient(stream ExampleRequest) returns (ExampleResponse);
    
      rpc StreamingBothWays(stream ExampleRequest) returns (stream ExampleResponse);
    }
    
    // The request message containing the user's name.
    message TestRequest {
      string name = 1;
    }
    
    // The response message containing the greetings.
    message TestReply {
      string message = 1;
    }
    
    message ExampleRequest{
    int32 pageIndex=1;
    int32 pageSize=2;
    bool isDescending=3;
    }
    
    message ExampleResponse{
    string name=1;
    string sex=2;
    }

    4、修改WebApplication1.csproj 文件,添加以下内容

      <ItemGroup>
        <Protobuf Include="Protosgreet.proto" GrpcServices="Client" />
      </ItemGroup>

    5、添加GrpcService文件夹,添加GrpcServer.cs

        public class GrpcServer
        {
            private readonly TestGrpc.TestGrpcClient _testGrpcClient;
            private readonly GrpcChannel _channel;
    
            public TestGrpc.TestGrpcClient MyGrpcClient
            {
                get { return _testGrpcClient; }
            }
            public GrpcServer()
            {
                _channel = GrpcChannel.ForAddress("http://localhost:5000");
                _testGrpcClient = new TestGrpc.TestGrpcClient(_channel);
            }
    
        }

    6、修改 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.AddControllersWithViews();
                services.AddSingleton<GrpcServer>(new GrpcServer());
            }
    
            // 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();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                app.UseHttpsRedirection();
                app.UseStaticFiles();
                
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }

    7、修改 Program.cs

    public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                        webBuilder.UseUrls("http://localhost:5003");
                    });
        }

    8、修改 HomeController.cs

     public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
            private readonly GrpcServer _grpcServer;
    
            public HomeController(ILogger<HomeController> logger,GrpcServer grpcServer)
            {
                _logger = logger;
                _grpcServer = grpcServer;
            }
    
            public IActionResult Index()
            {
                var ret = _grpcServer.MyGrpcClient.TestSay(new TestRequest { Name = "MyAspNetCoreMvc" });
                string msg = ret.Message;
                ViewData["GrpcMsg"] = msg;
                return View();
            }
    
            public IActionResult Privacy()
            {
                return View();
            }
    
            [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
            public IActionResult Error()
            {
                return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
            }
        }

    9、修改Index.cshtml

    @{
        ViewData["Title"] = "Home Page";
    }
    
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <h2>发送消息的用户:@ViewData["GrpcMsg"] </h2>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    </div>

     10、浏览器输入http://localhost:5003

  • 相关阅读:
    C#异步编程:多线程基础Thread类
    WPF:TextBox控件禁用中文输入
    C#:泛型的协变和逆变
    C#:泛型接口
    C#:泛型委托
    C#:泛型类
    Jetbrains Rider:缺少.NET Framework 4.5.2
    C#:泛型方法
    C#:泛型
    C#:接口
  • 原文地址:https://www.cnblogs.com/lhwpc/p/15181948.html
Copyright © 2011-2022 走看看