😬 [Blazor] gRPC-WEB 활용하기 🏭👩‍🏭👨‍🏭


순서

  1. Blazor 앱 생성
  2. NuGet 패키지 다운로드
  3. Protos 폴더생성 및 Protocol Buffer 추가
  4. 전체 빌드를 하여 proto파일 컴파일
  5. blazor 페이지에 코드 구현
  6. 통신결과

1. Blazor 앱 생성


해당글은 Server 앱을 가지고얘기합니다. WebAssembly 앱은 다릅니다.

K-001


.Net5

Startup.cs 추가

  1. ConfigureServices 에서 service.addCors(); 추가
  2. Configure 에서 app.UseGrpcWeb(); , app.UseCors(); 를 추가한다.

    app.UseRouting();app.UseEndpoints() 사이에 추가해야한다.

  3. EndPoints 에 endpoints.MapGrpcService().EnableGrpcWeb();

    서비스부분에 EnableGrpcWeb() 추가

.Net6

Program.cs 추가
app.UseRouting(); 다음에
app.UseGrpcWeb(); 를 추가한다.

K-007


2. NuGet 패키지 다운로드

K-002

Google.Protobuf
Grpc.Net.Client
Grpc.Tools

** 22.07.12 변경된 사항이 있다.

Grpc.Net.Client.Web <– 이것도 추가해야한다.


3. Protos 폴더생성 및 Protocol Buffer 추가

//폴더위치 
//Protos/CostCenter.proto 

syntax = "proto3";
option csharp_namespace = "CostCenterProto";

import "google/protobuf/timestamp.proto";

package CostCenterSvc;

message CostCenterRequest{
  int32 CenterType = 1;
}

message GrpcDecimal {
  int64 units = 1;
  sfixed32 nanos = 2;
}

message CostCenterResponse{
  string jsonResult = 1;
}

service CostCenter8 {
  rpc CostCenterList(CostCenterRequest) returns (CostCenterResponse);
}

Proto buffer를 생성을 해주고 전체빌드를 한다.

4. 전체 빌드를 하여 proto파일 컴파일

프로젝트를 빌드하고 나면 프로젝트명.csproj 에서 GrpcServices = “Client” 를 추가한다.

	<ItemGroup>
		<Protobuf Include="Protos\MesExample.proto" GrpcServices="Client" />
	</ItemGroup>

K-006

5. blazor 페이지에 코드 구현

<button class=”btn btn-primary” @onclick=”gRpc_Test”>Click me</button>

@using System.Threading.Tasks
@using Grpc.Net.Client
@using Grpc.Net.Client.Web
@using Mes.CostCenterProto
@inject IJSRuntime JSRuntime
@using System.Text.Json;
@using System.Text.Json.Serialization;
@using Newtonsoft.Json

@code {

    private string result = "";

    private async void gRpc_Test()
    {
        var channel = GrpcChannel.ForAddress("http://192.168.0.35:5215", new GrpcChannelOptions
            {
                HttpHandler = new GrpcWebHandler(new HttpClientHandler()),

            });

        var client = new CostCenter8.CostCenter8Client(channel);

        var reply = client.CostCenterList(new CostCenterRequest
            {
                CenterType = 1
            }
        );
        result = reply.JsonResult;

        string json = JsonConvert.SerializeObject(result);

        await JSRuntime.InvokeVoidAsync("console.log", "CostCenterList 결과 :", json);
    }

}

Console 출력부분 화면


Service 출력부분

Microsoft.AspNetCore.Routing.EndpointMiddleware: Information: Executed endpoint 'gRPC - /greet.Greeter/SayHello'
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished HTTP/2 POST http://localhost:50051/greet.Greeter/SayHello application/grpc-web - - 200 - application/grpc-web 7.0985ms

K-009

성공!!!

Note: 만들고나니 내것이 아니었다.

Leave a comment