Scenario:
Create a Sign on service to allow creation of users in our app. The web App calls this service to create the user and based on response update the UI.
Solution:
Create Unary Grpc service for sign on in .Net core 3.0.
per gRPC documentation
Unary RPCs where the client sends a single request to the server and gets a single response back, just like a normal function call.
- VS 2019 -> New Project -> gRPC Service -> GrpcServer
1
2
3
4
5
6
7
8
| namespace Web.Services
{
public static class CacheKeys
{
public static string Users { get { return "_allUsers"; } }
public static string CallbackMessage { get { return "_callbackMessage"; } }
}
}
|
- Create Service definition [proto file], name signon.proto and define the service as below
syntax = "proto3";
option csharp_namespace = "GrpcServer";
service SignOn {
rpc CreateNewUser (SignOnRequest) returns (SignOnResponse);
}
message SignOnRequest {
string email = 1;
string name = 2;
string password = 3;
}
message SignOnResponse {
bool sucess = 1;
string name = 2;
}
- Right click on the proto file and make sure below properties are correctly set
gRPC Stub Class
Server only
Protobuf
Class access = Public
- Override CreateNewUser in SignOnService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| public class SignOnService : SignOn.SignOnBase
{
public override Task<SignOnResponse> CreateNewUser(SignOnRequest request, ServerCallContext context)
{
var response = new SignOnResponse();
response.Sucess = false;
var json = JsonConvert.SerializeObject(request);
var elasticSearch = new ElasticSearchService();
//Post data to ELK
var success = elasticSearch.PostData(json, "ELK:indexes:userIndex");
if (success)
{
response = new SignOnResponse
{
Name = request.Name
};
}
}
|
- Create web project - VS 2019 -> New Project -> Web -> MyApp
- Add below nuget packages
1
2
3
| Google.Protobuff
Grp.Net.Client
Grpc.Tools
|
- Add Proto folder to project -> copy file signon.proto from server to here
- Invoke the service from client as below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| public IActionResult CreateNewUser(UserRequest userRequest)
{
try
{
var channel = GrpcChannel.ForAddress(grpServerUrl);
var client = new SignOn.SignOnClient(channel);
var response = client.CreateNewUser(new SignOnRequest
{
Email = userRequest.Email,
Name = userRequest.Name,
Password = userRequest.Password
});
ViewBag.success = true;
}
catch (Exception e)
{
throw e;
}
return View();
}
|
No comments:
Post a Comment