static void JRPCHandler(IApplicationBuilder app) { app.Run(async ctx => { ctx.Response.ContentType = "application/json"; var jres = new JRPCResponse(); try { string body; using (var sr = new StreamReader(ctx.Request.Body, encoding: Encoding.UTF8)) { body = sr.ReadToEnd(); } //var rpcReq = new RPCRequest { Ctx = ctx }; var rpcReq = new RPCRequest { AccessToken = GetJWT(ctx.Request.Headers) }; try { var jreq = RPCPacker.Unpack <JRPCRequest>(body); // allow methodName path e.g. /jrpc/{methodName} rpcReq.RPCFuncName = jreq.Method; if (string.IsNullOrWhiteSpace(rpcReq.RPCFuncName) && ctx.Request.Path.HasValue) { rpcReq.RPCFuncName = rxLeadingSlashs.Replace(ctx.Request.Path.Value, "").ToLower(); } // 允許 body 就直接是 PackedData e.g. { "Msg": "Hello" } rpcReq.PackedData = jreq.Params != null ? jreq.Params.ToString() : body; jres.Id = jreq.Id; } catch (Exception e) { jres.Error = new JRPCError(JRPCError.PARSE_ERROR, e.Message); await ctx.Response.WriteAsync(RPCPacker.Pack(jres, true)); } //var rpcResponse = await RPCServer.ExecuteAsync(rpcReq); //jres.Result = new JRaw(rpcResponse.PackedData); if (RPCServer.CheckAuthorized(rpcReq)) { var rpcResponse = await RPCServer.ExecuteAsync(rpcReq); jres.Result = new JRaw(rpcResponse.PackedData); } else { jres.Error = new JRPCError(401, "Permission denied", null); } } catch (JRPCException ex) { // 預期的錯誤 jres.Error = new JRPCError(1, ex.Message, null); ctx.Response.StatusCode = ex.HttpStatusCode; } catch (JRPCMethodNotFoundException ex) { jres.Error = new JRPCError(JRPCError.METHOD_NOT_FOUND, ex.Message); } catch (Newtonsoft.Json.JsonSerializationException ex) { jres.Error = new JRPCError(JRPCError.INVALID_PARAMS, ex.Message); } catch (Exception ex) { jres.Error = new JRPCError(JRPCError.INTERNAL_ERROR, ex.Message); } await ctx.Response.WriteAsync(RPCPacker.Pack(jres, true)); }); }