之後 就是 C# Server 端的 Code ,這邊包裝成 Web API 使用 Get 可以直接取得
using Dahomey.Cbor;
using Microsoft.AspNetCore.Mvc;
using System.Dynamic;
namespace TestCBOR
{
[Route("api/cbor")]
[ApiController]
public class CborController : ControllerBase
{
[HttpGet]
public IActionResult OnGet()
{
var stream = new MemoryStream();
dynamic obj = new Dahomey.Cbor.ObjectModel.CborObject();
obj.Name = "許當麻";
obj.Salary = 9876.5421;
obj.Id = "DONMA-ID";
Cbor.SerializeAsync(obj, stream).GetAwaiter().GetResult();
dynamic res = new ExpandoObject();
res.Id = Guid.NewGuid().ToString("N");
//如果沒有這樣做 你會被轉成 bse64
//這樣就是要轉成 byte[] 到前端
res.CborData = stream.ToArray().Select(x => x);
return new ObjectResult(res);
//result:
//{"Id":"52655a527e9547dabf90266c92fd301e","CborData":[163,100,78,97,109,101,105,232,168,177,231,149,182,233,186,187,102,83,97,108,97,114,121,251,64,195,74,69,99,136,101,149,98,73,100,104,68,79,78,77,65,45,73,68]}
}
}
}
沒意外的話跑起專案 直接打開 /api/cbor
2. 接下來就是 javascript 前端的部分
//cbor-js
//from
//https://github.com/paroga/cbor-js
$(document).ready(async function() {
let response;
try {
let res = await fetch("/api/cbor", {
method: 'GET'
});
response = await res.json();
//Array to Arraybuffer
var obj = new Uint8Array(response.CborData).buffer;
console.log(CBOR.decode(obj));
} catch (e) {
console.error("Request to server failed", e);
throw e;
}
});
Result:
大概就寫到這,其實還會有一些枚角我之後再補充
--
Before you read this, the article was in a superposition of human and AI. Upon observation, the wave function collapsed into a sleep-deprived developer.