asp.net core proto

 定义消息类型

//使用proto3版本,如果不写,默认使用proto2
syntax = "proto3";

option csharp_namespace = "GrpcServer.Protos";


message SearchRequest {
/*
每一个字段对应一个数值
数值1-15需要一个字节来编码,16-2047需要两个字节。
非常频繁发生的消息元素保留数字1-15,记得为频繁发生的元素留一些空间。
数值最小为1,最大为2的29次方 - 1。
数值19000-19999不允许使用,它们是保留给协议缓冲执行
*/
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}

字段规则

singular

message SearchRequest {
  //在正式传递时,不是必须固定是3个字段,可以小于3个  
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}

 repeated: 这个属性可以在一个正确的消息格式中重复任意次数(包括零次)??

message SearchRequest{
    repeated a=1
}

常用 prtpt类型与C#数据类型对照

proto类型   C#类型

double  double

float  float

int32  int

int64  long

bool  bool

string  string     字符串必须始终包含UTF-8编码或7位ASCII文本,且长度不能超过232

默认值

字符串默认为空

数值默认为0

布尔默认false

注释

//  或者 /*   */

保留字

如果已定义过的字段想要变动时,尽量不要删除,而是使用保留字reserved。不然可能引起数据损坏、隐私漏洞等问题。

message Foo {
  reserved 2, 15, 9 to 11;
  reserved "foo", "bar";
}

枚举

message SearchResponse {
  repeated Result results = 1;
}

message Result {
  string url = 1;
  string title = 2;
  repeated string snippets = 3;
}

导入另一个文件

import "myproject/other_protos.proto";

类型嵌套

message SearchResponse {
  message Result {
    string url = 1;
    string title = 2;
    repeated string snippets = 3;
  }
  repeated Result results = 1;
}

在其他地方使用该类型的子类

message SomeOtherMessage {
  SearchResponse.Result result = 1;
}

定义包名

package foo.bar;
message Open { ... }

使用包名

message Foo {
  ...
  foo.bar.Open open = 1;
  ...
}

服务

service SearchService {
  rpc Search(SearchRequest) returns (SearchResponse);
}

json映射

原文地址:https://www.cnblogs.com/buchizaodian/p/15474820.html