This article is a mirror article of machine translation, please click here to jump to the original article.

View: 59053|Reply: 9

[.NET Core] Practical combat: ASP.NET Core uses gRPC communication

[Copy link]
Posted on 11/11/2019 10:55:26 AM | | | |
grpc(The hyperlink login is visible.) is an open-source, high-performance, general-purpose RPC (Remote Procedure Call) framework released by Google, using the HTTP/2 protocol, supporting multiplexing, and using ProtoBuf as a serialization tool to provide cross-language and cross-platform support.
gRPC is a high-performance remote procedure call (RPC) framework that is language agnostic.

The main benefits of gRPC are:

  • Modern, high-performance, lightweight RPC framework.
  • Contract-first API development that uses protocol buffers by default, allowing for language-agnostic implementations.
  • Tools available in multiple languages to generate strongly typed servers and clients.
  • Supports client, server, and two-way streaming calls.
  • Reduce the use of the network with Protobuf binary serialization.


This article starts with . Net Core uses the gRPC protocol for client-side and server-side communication.

Create a gRPC server

Launch Visual Studio and select Create New Project. Alternatively, select New > Project from the Visual Studio File menu.

In the Create New Project dialog box, select gRPC Service, and then select Next:




After the creation is completed, as shown in the following figure:




Create a gRPC client

Open a second instance of Visual Studio and select Create a new project.
In the Create New Project dialog box, select Console App (.NET Core), and then select Next.
In the Name text box, enter gRPC-Client, and then select Create.


Add the required package

The gRPC client project requires the following packages:
Grpc.Net.Client, which contains the .NET Core client.
Google.Protobuf contains Protobuf messages for C#.
Grpc.Tools includes C# tool support for Protobuf files. The toolkit is not required at runtime, so the dependencies are marked as PrivateAssets="All".




Add greet.proto

Create a Protos folder in your gRPC client project.
Copy the Protos\greet.proto file from the gRPC Greeter service to the gRPC client project.

Edit the gRPC-Client.csproj project file, add the item group with the element that references the greet.proto file <Protobuf> :





Create a Greeter client

Update the gRPC client's Program.cs file with the following code:





Instantiate the GrpcChannel so that it contains the information used to create a connection to the gRPC service.
Construct a Greeter client using GrpcChannel.
The Greeter client calls the SayHello method. The result of the SayHello call is displayed.




Create your own .proto file communication

Create a new userinfo.proto file under the Protos folder of the serve, defined as follows:


gRPC uses a contract-first approach for API development. Define services and messages in the *.proto file.

Edit the GrpcService1.csproj project file, add the <Protobuf> item group with the element that references the userinfo.proto file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
    <Protobuf Include="Protos\userinfo.proto" GrpcServices="Server" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Grpc.AspNetCore" Version="2.23.1" />
  </ItemGroup>

</Project>


Create a new UserInfoService.cs file under the Services folder, the code is as follows:

Register the UserInfoService service on Startup.cs with the following code:

Leaving aside the client, of course, you need to copy the userinfo.proto file past, and the code is as follows:

Return value:

Hello World!
Response: Hello itsvse.com
{ "id": "1", "name": "architect", "age": 5, "isVip": true }
{ "id": "2", "name": "itsvse.com", "age": 5 }
Unhandled exception. Grpc.Core.RpcException: Status(StatusCode=Cancelled, Detail="No message returned from method.")
   at Grpc.Net.Client.Internal.HttpClientCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at Grpc.Core.Interceptors.InterceptingCallInvoker. <BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext`2 ctx)
   at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext`2 context, BlockingUnaryCallContinuation`2 continuation)
   at Grpc.Core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest request, CallOptions options) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\ UserinfoGrpc.cs:line 62
   at UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest request, Metadata headers, Nullable`1 deadline, CancellationToken cancellationToken) in C: \Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\UserinfoGrpc.cs:line 58
   at gRPC_Client.Program.Main(String[] args) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\Program.cs:line 20
Please press any key to continue. . . .


When the return value is null, the client throws an exception.


Fiddler grab the bag

To try to use Fiddler to capture packets, first set up the proxy on the client as follows (in fact, you can not set it up, just open Fiddler directly):

Error on the server side:

fail: Microsoft.AspNetCore.Server.Kestrel[0]
      HTTP/2 over TLS was not negotiated on an HTTP/2-only endpoint.
Client error:

Unhandled exception. Grpc.Core.RpcException: Status(StatusCode=Internal, Detail="Bad gRPC response. Response protocol downgraded to HTTP/1.1.")
   at Grpc.Net.Client.Internal.HttpClientCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at Grpc.Core.Interceptors.InterceptingCallInvoker. <BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext`2 ctx)
   at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext`2 context, BlockingUnaryCallContinuation`2 continuation)
   at Grpc.Core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest request, CallOptions options) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\ UserinfoGrpc.cs:line 62
   at UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest request, Metadata headers, Nullable`1 deadline, CancellationToken cancellationToken) in C: \Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\UserinfoGrpc.cs:line 58
   at gRPC_Client.Program.Main(String[] args) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\Program.cs:line 23
Please press any key to continue. . . .


POST address: https://localhost:5001/UserInfo/GetUserInfo

Content:

Host: localhost:5001
User-Agent: grpc-dotnet/2.25.0.0
TE: trailers
grpc-accept-encoding: identity,gzip
Content-Type: application/grpc
Content-Length: 7
Fiddler-Encoding: base64


Finally, attach the source code:

Tourists, if you want to see the hidden content of this post, pleaseReply


(End)




Previous:Programmer's Refinement: From Novice to Engineer Full PDF
Next:100 lossless pot music
Posted on 11/11/2019 5:46:30 PM |
ASP.NET Core uses gRPC communication
Posted on 11/28/2019 3:14:53 PM |
ASP.NET Core uses gRPC communication
Posted on 11/28/2019 3:15:25 PM |
ASP.NET Core uses gRPC communication
Posted on 12/2/2020 3:52:18 PM |
How did you solve this last mistake?
Posted on 12/7/2020 8:37:56 PM |
using Grpc.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GrpcService1
{
    public class UserInfoService : UserInfo.UserInfoBase
    {
        private readonly ILogger<UserInfoService> _logger;
        private static List<UserInfoReply> userInfoReplies = new List<UserInfoReply>();
        static UserInfoService()
        {
            userInfoReplies.Add(new UserInfoReply()
            {
                Id = 1,
                Name = "Architect",
                Age = 5,
                IsVip = true
            });
            userInfoReplies.Add(new UserInfoReply()
            {
                Id = 2,
                Name = "itsvse.com",
                Age = 5,
                IsVip = false
            });
            userInfoReplies.Add(new UserInfoReply()
            {
                Id = 3,
                Name = "Little Scum",
                Age = 1,
                IsVip = false
            });
        }
        public UserInfoService(ILogger<UserInfoService> logger)
        {
            _logger = logger;
        }

        public override Task<UserInfoReply> GetUserInfo(GetUserInfoRequest request, ServerCallContext context)
        {
            return Task.Run(() =>
            {
                return userInfoReplies.SingleOrDefault(x => x.Id == request. Id);
            });
        }
    }
}
Posted on 12/7/2020 9:06:17 PM |
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Grpc.Net.Client.Internal.HttpClientCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at Grpc.Core.Interceptors.InterceptingCallInvoker. <BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext`2 ctx)
   at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext`2 context, BlockingUnaryCallContinuation`2 continuation)
   at Grpc.Core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
Posted on 5/25/2021 11:37:34 AM |
It's really well written, praise and praise
Posted on 6/5/2021 11:45:21 AM |
ASP.NET Core uses gRPC communication
 Landlord| Posted on 8/13/2025 3:25:35 PM |
Use Postman to test (debug) the gRPC service
https://www.itsvse.com/thread-11053-1-1.html
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com