这是一个带有RestClient.Net的原型定义、后端和前端代码的示例。
原型定义
message Person {
string PersonKey = 1;
string FirstName = 2;
string Surname=3;
Address BillingAddress = 4;
}
message Address {
string AddressKey = 1;
string StreeNumber = 2;
string Street=3;
string Suburb=4;
}
Code Reference
控制器:
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
var person = new Person
{
FirstName = "Sam",
BillingAddress = new Address
{
StreeNumber = "100",
Street = "Somewhere",
Suburb = "Sometown"
},
Surname = "Smith"
};
var data = person.ToByteArray();
return File(data, "application/octet-stream");
}
[HttpPost]
public async Task<IActionResult> Post()
{
var stream = Request.BodyReader.AsStream();
return File(stream, "application/octet-stream");
}
[HttpPut]
public async Task<IActionResult> Put()
{
var stream = Request.BodyReader.AsStream();
var person = Person.Parser.ParseFrom(stream);
if (!Request.Headers.ContainsKey("PersonKey")) throw new Exception("No key");
person.PersonKey = Request.Headers["PersonKey"];
var data = person.ToByteArray();
return File(data, "application/octet-stream");
}
}
Code Reference
序列化:
public class ProtobufSerializationAdapter : ISerializationAdapter
{
public byte[] Serialize<TRequestBody>(TRequestBody value, IHeadersCollection requestHeaders)
{
var message = (IMessage)value as IMessage;
if (message == null) throw new Exception("The object is not a Google Protobuf Message");
return message.ToByteArray();
}
public TResponseBody Deserialize<TResponseBody>(byte[] data, IHeadersCollection responseHeaders)
{
var messageType = typeof(TResponseBody);
var parserProperty = messageType.GetProperty("Parser");
var parser = parserProperty.GetValue(parserProperty);
var parseFromMethod = parserProperty.PropertyType.GetMethod("ParseFrom", new Type[] { typeof(byte[]) });
var parsedObject = parseFromMethod.Invoke(parser,new object[] { data });
return (TResponseBody)parsedObject;
}
}
Code Reference
用法:
var person = new Person { FirstName = "Bob", Surname = "Smith" };
var client = new Client(new ProtobufSerializationAdapter(), new Uri("http://localhost:42908/person"));
person = await client.PostAsync<Person, Person>(person);
Code Reference