├── test ├── EdjCase.JsonRpc.Client.Sample │ ├── runtimeconfig.template.json │ ├── EdjCase.JsonRpc.Client.Sample.csproj │ └── Program.cs ├── EdjCase.JsonRpc.Router.Sample │ ├── runtimeconfig.template.json │ ├── Properties │ │ └── launchSettings.json │ ├── web.config │ ├── wwwroot │ │ └── web.config │ ├── Controllers │ │ ├── ApiController.cs │ │ └── ComplexExampleController.cs │ ├── EdjCase.JsonRpc.Router.Sample.csproj │ ├── RpcControllers.cs │ └── Startup.cs ├── EdjCase.JsonRpc.Router.Tests │ ├── Controllers │ │ ├── MethodMatcherThreeController.cs │ │ ├── MethodMatcherDuplicatesController.cs │ │ └── MethodMatcherController.cs │ ├── FakeLogger.cs │ ├── EdjCase.JsonRpc.Router.Tests.csproj │ ├── RpcUtilTests.cs │ ├── SerializerTests.cs │ ├── RpcParameterConverterTests.cs │ └── RequestSignatureTests.cs ├── Benchmarks │ ├── Benchmarks.csproj │ ├── BasicTests.websurge │ └── Program.cs └── EdjCase.JsonRpc.Client.Tests │ ├── EdjCase.JsonRpc.Client.Tests.csproj │ └── HttpTransportClientTests.cs ├── .vscode ├── settings.json ├── tasks.json └── launch.json ├── .travis.yml ├── src ├── EdjCase.JsonRpc.Client │ ├── Publish.cmd │ ├── Constants.cs │ ├── DefaultHttpClientFactory.cs │ ├── IHttpAuthHeaderFactory.cs │ ├── RpcBulkResponse.cs │ ├── EdjCase.JsonRpc.Client.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── RpcEvents.cs │ ├── RpcBulkRequest.cs │ ├── RpcResponse.cs │ ├── RpcParameters.cs │ ├── RpcClientExceptions.cs │ ├── RpcRequest.cs │ ├── HttpClientBuilder.cs │ ├── RpcTransportClients.cs │ └── DefaultRequestSerializer.cs ├── EdjCase.JsonRpc.Router │ ├── Publish.cmd │ ├── Utilities │ │ ├── StreamUtil.cs │ │ ├── ExtensionsUtil.cs │ │ ├── RpcUtil.cs │ │ └── JsonStringGeneratorUtil.cs │ ├── Abstractions │ │ ├── IRpcParameterConverter.cs │ │ ├── IRpcAuthorizationHandler.cs │ │ ├── IRpcRequestMatcher.cs │ │ ├── IRpcContext.cs │ │ ├── IRpcMethodResult.cs │ │ ├── IRpcInvoker.cs │ │ ├── IRpcParser.cs │ │ ├── IRpcResponseSerializer.cs │ │ ├── IRpcMethodProvider.cs │ │ └── IRpcRequestHandler.cs │ ├── .editorconfig │ ├── StaticRpcMethodProvider.cs │ ├── Defaults │ │ ├── DefaultRpcContext.cs │ │ ├── DefaultRpcMethodResults.cs │ │ ├── DefaultAuthorizationHandler.cs │ │ └── DefaultRpcResponseSerializer.cs │ ├── RpcRouterExceptions.cs │ ├── RpcResponse.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── EdjCase.JsonRpc.Router.csproj │ ├── RpcRequest.cs │ ├── RpcController.cs │ ├── RpcNumber.cs │ ├── ParsingResult.cs │ ├── IRpcParameter.cs │ ├── RpcEndpointBuilder.cs │ ├── RpcMethodInfo.cs │ ├── Configuration.cs │ ├── RpcHttpRouter.cs │ ├── RpcRequestHandler.cs │ ├── RpcPath.cs │ └── BuilderExtensions.cs ├── EdjCase.JsonRpc.Router.Swagger │ ├── Publish.cmd │ ├── Models │ │ ├── SwaggerConfiguration.cs │ │ └── RpcRouteMethodInfo.cs │ ├── EdjCase.JsonRpc.Router.Swagger.csproj │ ├── BuilderExtensions.cs │ └── IXmlDocumentationService.cs └── EdjCase.JsonRpc.Common │ ├── Constants.cs │ ├── EdjCase.JsonRpc.Common.projitems │ ├── Utilities │ └── ExtensionsUtil.cs │ ├── EdjCase.JsonRpc.Common.shproj │ ├── Tools │ └── StreamCompressors.cs │ ├── RpcExceptions.cs │ ├── RpcError.cs │ └── RpcId.cs ├── Nuget.config ├── .editorconfig ├── publish.sh ├── Publish.cmd ├── .github └── workflows │ ├── build_and_test.yml │ └── release.yml ├── LICENSE ├── .gitignore └── EdjCase.JsonRpc.sln /test/EdjCase.JsonRpc.Client.Sample/runtimeconfig.template.json: -------------------------------------------------------------------------------- 1 | { 2 | "gcServer": true 3 | } -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/runtimeconfig.template.json: -------------------------------------------------------------------------------- 1 | { 2 | "gcServer": true 3 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.insertSpaces": false, 3 | "dotnet-test-explorer.testProjectPath": "**/*Tests.@(csproj|vbproj|fsproj)" 4 | } -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | solution: EdjCase.JsonRpc.sln 3 | mono: none 4 | dotnet: 3.1.1 5 | script: 6 | - chmod a+x ./publish.sh 7 | - ./publish.sh 8 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/Publish.cmd: -------------------------------------------------------------------------------- 1 | SET configuration=Release 2 | SET out=C:\Publish 3 | 4 | call dotnet pack -c %configuration% -o "%out%/EdjCase.JsonRpc.Client" -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Publish.cmd: -------------------------------------------------------------------------------- 1 | SET configuration=Release 2 | SET out=C:\Publish 3 | 4 | call dotnet pack -c %configuration% -o "%out%/EdjCase.JsonRpc.Router" -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router.Swagger/Publish.cmd: -------------------------------------------------------------------------------- 1 | SET configuration=Release 2 | SET out=C:\Publish 3 | 4 | call dotnet pack -c %configuration% -o "%out%/EdjCase.JsonRpc.Router.Swagger" -------------------------------------------------------------------------------- /Nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | charset = utf-8 3 | end_of_line = lf 4 | 5 | [*.{cs,razor}] 6 | dotnet_style_qualification_for_property = true:error 7 | dotnet_style_qualification_for_field = true:error 8 | dotnet_style_qualification_for_event = true:error 9 | dotnet_style_qualification_for_method = true:error 10 | indent_style = tab -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/Controllers/MethodMatcherThreeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EdjCase.JsonRpc.Router.Tests.Controllers 4 | { 5 | public class MethodMatcherThreeController 6 | { 7 | public Guid GuidTypeMethod(Guid guid) 8 | { 9 | return guid; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/Controllers/MethodMatcherDuplicatesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EdjCase.JsonRpc.Router.Tests.Controllers 4 | { 5 | public class MethodMatcherDuplicatesController 6 | { 7 | public Guid GuidTypeMethod(Guid guid) 8 | { 9 | return guid; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router.Swagger/Models/SwaggerConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | 3 | namespace EdjCase.JsonRpc.Router.Swagger.Models 4 | { 5 | public class SwaggerConfiguration 6 | { 7 | public string[] Endpoints { get; set; } = new string[0]; 8 | public JsonNamingPolicy NamingPolicy { get; set; } = JsonNamingPolicy.CamelCase; 9 | } 10 | } -------------------------------------------------------------------------------- /publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | dotnet test ./test/EdjCase.JsonRpc.Router.Tests -c Release 4 | 5 | dotnet pack ./src/EdjCase.JsonRpc.Router -c Release -o "./out/EdjCase.JsonRpc.Router" 6 | 7 | dotnet pack ./src/EdjCase.JsonRpc.Router.Swagger -c Release -o "./out/EdjCase.JsonRpc.Router.Swagger" 8 | 9 | dotnet pack ./src/EdjCase.JsonRpc.Client -c Release -o "out/EdjCase.JsonRpc.Client" -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Web": { 4 | "commandName": "Project", 5 | "launchBrowser": true, 6 | "launchUrl": "http://localhost:5000/swagger/index.html", 7 | "environmentVariables": { 8 | "ASPNETCORE_URLS": "http://localhost:5000", 9 | "ASPNETCORE_ENVIRONMENT": "Development" 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/web.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/Constants.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace EdjCase.JsonRpc.Client 7 | { 8 | public static class Defaults 9 | { 10 | public const string ContentType = "application/json"; 11 | public static readonly Encoding Encoding = Encoding.UTF8; 12 | public static List<(string, string)> GetHeaders() => new List<(string, string)> { ("Accept-Encoding", "gzip, deflate") }; 13 | } 14 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router.Swagger/Models/RpcRouteMethodInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using EdjCase.JsonRpc.Router.Abstractions; 3 | 4 | namespace EdjCase.JsonRpc.Router.Swagger.Models 5 | { 6 | public class UniqueMethod 7 | { 8 | public string UniqueUrl { get; } 9 | public IRpcMethodInfo Info { get; } 10 | 11 | public UniqueMethod(string uniqueUrl, IRpcMethodInfo info) 12 | { 13 | this.UniqueUrl = uniqueUrl; 14 | this.Info = info; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Utilities/StreamUtil.cs: -------------------------------------------------------------------------------- 1 | using System.Buffers; 2 | using System.IO; 3 | using System.Text; 4 | 5 | namespace EdjCase.JsonRpc.Router.Utilities 6 | { 7 | internal class StreamUtil 8 | { 9 | internal static MemoryStream GetStreamFromUtf8String(string utf8Text) 10 | { 11 | byte[] bytes = ArrayPool.Shared.Rent(Encoding.UTF8.GetByteCount(utf8Text)); 12 | int byteCount = Encoding.UTF8.GetBytes(utf8Text, 0, utf8Text.Length, bytes, 0); 13 | return new MemoryStream(bytes, 0, byteCount); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Publish.cmd: -------------------------------------------------------------------------------- 1 | SET configuration=Release 2 | SET out=C:/Publish 3 | 4 | call dotnet test ./test/EdjCase.JsonRpc.Router.Tests -c %configuration% 5 | 6 | call dotnet pack ./src/EdjCase.JsonRpc.Router -c %configuration% -o "%out%/EdjCase.JsonRpc.Router" 7 | 8 | call dotnet pack ./src/EdjCase.JsonRpc.Router.Swagger -c %configuration% -o "%out%/EdjCase.JsonRpc.Router.Swagger" 9 | 10 | call dotnet test ./test/EdjCase.JsonRpc.Client.Tests -c %configuration% 11 | 12 | call dotnet pack ./src/EdjCase.JsonRpc.Client -c %configuration% -o "%out%/EdjCase.JsonRpc.Client" 13 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcParameterConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace EdjCase.JsonRpc.Router.Abstractions 6 | { 7 | public interface IRpcParameterConverter 8 | { 9 | bool AreTypesCompatible(RpcParameterType sourceType, RpcParameterType destinationType); 10 | bool TryConvertValue(RpcParameter sourceValue, RpcParameterType destinationType, Type destinationRawType, out object? destinationValue, out Exception? exception); 11 | RpcParameterType GetRpcParameterType(Type type); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/Benchmarks/Benchmarks.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | net6.0 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcAuthorizationHandler.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router.Utilities; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | using System.Collections.Concurrent; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Reflection; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace EdjCase.JsonRpc.Router.Abstractions 13 | { 14 | internal interface IRpcAuthorizationHandler 15 | { 16 | Task IsAuthorizedAsync(IRpcMethodInfo methodInfo); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | 3 | # CS8625: Cannot convert null literal to non-nullable reference type. 4 | dotnet_diagnostic.CS8625.severity = error 5 | 6 | # CS8618: Non-nullable field is uninitialized. Consider declaring as nullable. 7 | dotnet_diagnostic.CS8618.severity = error 8 | 9 | # CS8604: Possible null reference argument. 10 | dotnet_diagnostic.CS8604.severity = error 11 | 12 | # CS8600: Converting null literal or possible null value to non-nullable type. 13 | dotnet_diagnostic.CS8600.severity = error 14 | 15 | # CS8603: Possible null reference return. 16 | dotnet_diagnostic.CS8603.severity = error 17 | -------------------------------------------------------------------------------- /.github/workflows/build_and_test.yml: -------------------------------------------------------------------------------- 1 | name: .NET 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | types: 8 | - opened 9 | - synchronized 10 | 11 | jobs: 12 | build: 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: Setup .NET 19 | uses: actions/setup-dotnet@v2 20 | with: 21 | dotnet-version: 6.0.x 22 | - name: Restore dependencies 23 | run: dotnet restore 24 | - name: Build 25 | run: dotnet build --no-restore 26 | - name: Test 27 | run: dotnet test --no-build --verbosity normal 28 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcRequestMatcher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using EdjCase.JsonRpc.Router; 5 | using EdjCase.JsonRpc.Common; 6 | 7 | namespace EdjCase.JsonRpc.Router.Abstractions 8 | { 9 | internal interface IRpcRequestMatcher 10 | { 11 | /// 12 | /// Finds the matching Rpc method for the current request 13 | /// 14 | /// Current Rpc request 15 | /// The matching Rpc method to the current request 16 | IRpcMethodInfo GetMatchingMethod(RpcRequestSignature requestSignature); 17 | } 18 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcContext.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router; 2 | using EdjCase.JsonRpc.Router.Abstractions; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | using System.Security.Claims; 7 | 8 | namespace EdjCase.JsonRpc.Router.Abstractions 9 | { 10 | public class RpcContext 11 | { 12 | public IServiceProvider RequestServices { get; } 13 | public RpcPath? Path { get; } 14 | 15 | public RpcContext(IServiceProvider serviceProvider, RpcPath? path = null) 16 | { 17 | this.RequestServices = serviceProvider; 18 | this.Path = path; 19 | } 20 | } 21 | 22 | internal interface IRpcContextAccessor 23 | { 24 | RpcContext Get(); 25 | void Set(RpcContext context); 26 | } 27 | } -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/FakeLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using EdjCase.JsonRpc.Router.Defaults; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace EdjCase.JsonRpc.Router.Tests 6 | { 7 | internal class FakeLogger : ILogger 8 | { 9 | public IDisposable? BeginScope(TState state) where TState : notnull 10 | { 11 | return new FakeDisposable(); 12 | } 13 | 14 | public bool IsEnabled(LogLevel logLevel) 15 | { 16 | return false; 17 | } 18 | 19 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) 20 | { 21 | 22 | } 23 | } 24 | 25 | internal class FakeDisposable : IDisposable 26 | { 27 | public void Dispose() 28 | { 29 | 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcMethodResult.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace EdjCase.JsonRpc.Router.Abstractions 8 | { 9 | /// 10 | /// Rpc method response object that allows the server to customize an rpc response 11 | /// 12 | public interface IRpcMethodResult 13 | { 14 | /// 15 | /// Turns result data into a rpc response 16 | /// 17 | /// Rpc request id 18 | /// Json serializer function to use for objects for the response 19 | /// Rpc response for request 20 | RpcResponse ToRpcResponse(RpcId id); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/wwwroot/web.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/Controllers/ApiController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace EdjCase.JsonRpc.Router.Sample.Controllers; 4 | 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class ApiController : Microsoft.AspNetCore.Mvc.ControllerBase 8 | { 9 | [HttpGet("{id}")] 10 | public IActionResult GetById(int id) 11 | { 12 | var result = new 13 | { 14 | Id = id, 15 | Description = $"This is an Api call {id}." 16 | }; 17 | 18 | return (IActionResult)this.Ok(result); 19 | } 20 | } 21 | 22 | [RpcRoute("NonApi")] 23 | public class NonApiController : RpcController 24 | { 25 | 26 | public object GetById(int id) 27 | { 28 | var result = new 29 | { 30 | Id = id, 31 | Description = $"This is bar {id}." 32 | }; 33 | 34 | return result; 35 | } 36 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcInvoker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace EdjCase.JsonRpc.Router.Abstractions 6 | { 7 | internal interface IRpcInvoker 8 | { 9 | /// 10 | /// Call the incoming Rpc request method and gives the appropriate response 11 | /// 12 | /// Rpc request 13 | /// An Rpc response for the request 14 | Task InvokeRequestAsync(RpcRequest request); 15 | 16 | /// 17 | /// Call the incoming Rpc requests methods and gives the appropriate respones 18 | /// 19 | /// List of Rpc requests to invoke 20 | /// List of Rpc responses for the requests 21 | Task> InvokeBatchRequestAsync(IList requests); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/StaticRpcMethodProvider.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router.Abstractions; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | 7 | namespace EdjCase.JsonRpc.Router 8 | { 9 | internal class StaticRpcMethodProvider : IRpcMethodProvider 10 | { 11 | private StaticRpcMethodDataAccessor dataAccessor { get; } 12 | 13 | public StaticRpcMethodProvider(StaticRpcMethodDataAccessor dataAccessor) 14 | { 15 | this.dataAccessor = dataAccessor; 16 | } 17 | 18 | public RpcRouteMetaData Get() 19 | { 20 | if (this.dataAccessor.Value == null) 21 | { 22 | throw new RpcConfigurationException("Rpc routes are not configured."); 23 | } 24 | return this.dataAccessor.Value; 25 | } 26 | } 27 | 28 | internal class StaticRpcMethodDataAccessor 29 | { 30 | public RpcRouteMetaData? Value { get; set; } 31 | } 32 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace EdjCase.JsonRpc.Common 2 | { 3 | /// 4 | /// Error codes for different Rpc errors 5 | /// 6 | public enum RpcErrorCode 7 | { 8 | ParseError = -32700, 9 | InvalidRequest = -32600, 10 | MethodNotFound = -32601, 11 | InvalidParams = -32602, 12 | InternalError = -32603 13 | } 14 | 15 | public static class JsonRpcContants 16 | { 17 | public const string VersionPropertyName = "jsonrpc"; 18 | public const string MethodPropertyName = "method"; 19 | public const string ParamsPropertyName = "params"; 20 | public const string IdPropertyName = "id"; 21 | public const string ResultPropertyName = "result"; 22 | public const string ErrorPropertyName = "error"; 23 | public const string ErrorCodePropertyName = "code"; 24 | public const string ErrorMessagePropertyName = "message"; 25 | public const string ErrorDataPropertyName = "data"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Client.Tests/EdjCase.JsonRpc.Client.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | false 6 | true 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Buffers; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | using EdjCase.JsonRpc.Router; 7 | using EdjCase.JsonRpc.Common; 8 | using EdjCase.JsonRpc.Router.Utilities; 9 | 10 | namespace EdjCase.JsonRpc.Router.Abstractions 11 | { 12 | internal interface IRpcParser 13 | { 14 | /// 15 | /// Parses all the requests from the json in the request 16 | /// 17 | /// Json stream to parse from 18 | /// Result of the parsing. Includes all the parsed requests and any errors 19 | ParsingResult ParseRequests(Stream jsonStream); 20 | 21 | public virtual ParsingResult ParseRequests(string json) 22 | { 23 | using (var stream = StreamUtil.GetStreamFromUtf8String(json ?? string.Empty)) 24 | { 25 | return this.ParseRequests(stream); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Defaults/DefaultRpcContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Security.Claims; 6 | using System.Threading.Tasks; 7 | using EdjCase.JsonRpc.Router.Abstractions; 8 | using Microsoft.AspNetCore.Http; 9 | 10 | namespace EdjCase.JsonRpc.Router.Defaults 11 | { 12 | 13 | internal class DefaultContextAccessor : IRpcContextAccessor 14 | { 15 | private RpcContext? value; 16 | 17 | public RpcContext Get() 18 | { 19 | if (this.value == null) 20 | { 21 | throw new InvalidOperationException("Cannot access rpc context outside of a rpc request scope"); 22 | } 23 | return this.value; 24 | } 25 | 26 | public void Set(RpcContext context) 27 | { 28 | if (this.value != null) 29 | { 30 | throw new InvalidOperationException("Cannot set rpc context multiple times"); 31 | } 32 | this.value = context; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/DefaultHttpClientFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Net.Http; 4 | 5 | namespace EdjCase.JsonRpc.Client 6 | { 7 | 8 | internal class DefaultHttpClientFactory : IHttpClientFactory, IDisposable 9 | { 10 | public ConcurrentDictionary Clients { get; } = new ConcurrentDictionary(); 11 | 12 | public HttpMessageHandler? MessageHandler { get; } 13 | public DefaultHttpClientFactory(HttpMessageHandler? handler = null) 14 | { 15 | this.MessageHandler = handler; 16 | } 17 | 18 | public HttpClient CreateClient(string name) 19 | { 20 | return this.Clients.GetOrAdd(name, BuildClient); 21 | 22 | HttpClient BuildClient(string n) 23 | { 24 | return this.MessageHandler == null ? new HttpClient() : new HttpClient(this.MessageHandler); 25 | } 26 | } 27 | 28 | public void Dispose() 29 | { 30 | foreach (HttpClient client in this.Clients.Values) 31 | { 32 | client?.Dispose(); 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/EdjCase.JsonRpc.Common.projitems: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath) 5 | true 6 | 1546452e-2db4-421c-90cd-b4b310ce9ad9 7 | 8 | 9 | EdjCase.JsonRpc.Common 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/EdjCase.JsonRpc.Router.Sample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1591 6 | net6.0 7 | EdjCase.JsonRpc.Router.Sample 8 | EdjCase.JsonRpc.Router.Sample 9 | bd997694-63b3-4cf8-8798-f7274f180573 10 | 11 | 12 | 13 | bin\Debug\EdjCase.JsonRpc.Router.Sample.xml 14 | 15 | 16 | 17 | bin\Release\EdjCase.JsonRpc.Router.Sample.xml 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/Utilities/ExtensionsUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace EdjCase.JsonRpc.Common.Utilities 6 | { 7 | public static class TypeExtensions 8 | { 9 | /// 10 | /// Determines if the type is a number 11 | /// 12 | /// Type of the object 13 | /// Includes a check for whole number types. Defaults to true 14 | /// True if the type is a number, otherwise False 15 | public static bool IsNumericType(this Type type, bool includeInteger = true) 16 | { 17 | if (includeInteger) 18 | { 19 | return type == typeof(long) 20 | || type == typeof(int) 21 | || type == typeof(short) 22 | || type == typeof(float) 23 | || type == typeof(double) 24 | || type == typeof(decimal); 25 | } 26 | else 27 | { 28 | return type == typeof(float) 29 | || type == typeof(double) 30 | || type == typeof(decimal); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Client.Sample/EdjCase.JsonRpc.Client.Sample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A Client sample for Json Rpc v2 requests for .Net Core. 5 | JsonRpc .Net Core Client Sample 6 | Gekctek 7 | net6.0 8 | true 9 | EdjCase.JsonRpc.Client.Sample 10 | Exe 11 | EdjCase.JsonRpc.Client.Sample 12 | https://github.com/edjCase/JsonRpc 13 | https://raw.githubusercontent.com/edjCase/JsonRpc/master/LICENSE 14 | git 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/RpcControllers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace EdjCase.JsonRpc.Router.Sample 7 | { 8 | public abstract class ControllerBase : RpcController 9 | { 10 | 11 | } 12 | 13 | [RpcRoute("Main")] 14 | public class CustomController : ControllerBase 15 | { 16 | [RpcRoute("Method")] 17 | public string Method1(string a) 18 | { 19 | return a; 20 | } 21 | } 22 | public class OtherController : ControllerBase 23 | { 24 | public string Method1(string a) 25 | { 26 | return a; 27 | } 28 | } 29 | public class Commands : ControllerBase 30 | { 31 | public string Method1(string a) 32 | { 33 | return a; 34 | } 35 | } 36 | public class Test : RpcController 37 | { 38 | public string Method1(string a) 39 | { 40 | return a; 41 | } 42 | [NonRpcMethod] 43 | public string Method2(string a) 44 | { 45 | return a; 46 | } 47 | } 48 | 49 | public class NonRpcController 50 | { 51 | public string Method1(string a) 52 | { 53 | return a; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/EdjCase.JsonRpc.Common.shproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 1546452e-2db4-421c-90cd-b4b310ce9ad9 5 | 14.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2015 Gekctek 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/IHttpAuthHeaderFactory.cs: -------------------------------------------------------------------------------- 1 | 2 | using EdjCase.JsonRpc.Common; 3 | using EdjCase.JsonRpc.Common.Tools; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.IO.Compression; 8 | using System.Linq; 9 | using System.Net.Http; 10 | using System.Net.Http.Headers; 11 | using System.Text; 12 | using System.Threading; 13 | using System.Threading.Tasks; 14 | 15 | namespace EdjCase.JsonRpc.Client 16 | { 17 | public interface IHttpAuthHeaderFactory 18 | { 19 | Task CreateAuthHeader(); 20 | } 21 | 22 | public class DefaultHttpAuthHeaderFactory : IHttpAuthHeaderFactory 23 | { 24 | private Func> authHeaderFunc { get; } 25 | public DefaultHttpAuthHeaderFactory(Func>? authHeaderFunc = null) 26 | { 27 | this.authHeaderFunc = authHeaderFunc ?? (() => Task.FromResult(null)); 28 | } 29 | public DefaultHttpAuthHeaderFactory(AuthenticationHeaderValue? authHeader) 30 | { 31 | this.authHeaderFunc = () => Task.FromResult(authHeader); 32 | } 33 | 34 | public Task CreateAuthHeader() 35 | { 36 | return this.authHeaderFunc(); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcResponseSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using EdjCase.JsonRpc.Common; 7 | 8 | namespace EdjCase.JsonRpc.Router.Abstractions 9 | { 10 | internal interface IRpcResponseSerializer 11 | { 12 | Task SerializeAsync(RpcResponse response, Stream stream); 13 | Task SerializeBulkAsync(IEnumerable responses, Stream stream); 14 | 15 | public virtual async Task SerializeAsync(RpcResponse response) 16 | { 17 | using var stream = new MemoryStream(); 18 | await this.SerializeAsync(response, stream); 19 | return await IRpcResponseSerializer.GetStringAsync(stream); 20 | } 21 | 22 | public virtual async Task SerializeBulkAsync(IEnumerable responses) 23 | { 24 | using var stream = new MemoryStream(); 25 | await this.SerializeBulkAsync(responses, stream); 26 | return await IRpcResponseSerializer.GetStringAsync(stream); 27 | } 28 | 29 | private static Task GetStringAsync(MemoryStream stream) 30 | { 31 | stream.Position = 0; 32 | using var streamReader = new StreamReader(stream); 33 | return streamReader.ReadToEndAsync(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Utilities/ExtensionsUtil.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Routing; 2 | using Microsoft.Extensions.Logging; 3 | using Microsoft.Extensions.Options; 4 | using System; 5 | using System.Text.Json; 6 | using System.Threading.Tasks; 7 | 8 | namespace EdjCase.JsonRpc.Router.Utilities 9 | { 10 | internal static class TypeExtensions 11 | { 12 | /// 13 | /// Determines if the type is nullable 14 | /// 15 | /// Type of the object 16 | /// True if the type is nullable, otherwise False 17 | public static bool IsNullableType(this Type type) 18 | { 19 | return !type.IsValueType || Nullable.GetUnderlyingType(type) != null; 20 | } 21 | 22 | public static JsonWriterOptions ToWriterOptions(this JsonSerializerOptions? options) 23 | { 24 | JsonWriterOptions writerOptions = default; 25 | if (options != null) 26 | { 27 | writerOptions.Encoder = options.Encoder; 28 | writerOptions.Indented = options.WriteIndented; 29 | } 30 | return writerOptions; 31 | } 32 | } 33 | 34 | internal static class RouteContextExtensions 35 | { 36 | public static void MarkAsHandled(this RouteContext context) 37 | { 38 | context.Handler = c => Task.FromResult(0); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish Release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | jobs: 7 | publish: 8 | name: Publish 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | 13 | - name: Setup Dotnet 14 | uses: actions/setup-dotnet@v1 15 | with: 16 | dotnet-version: 6.0.x 17 | 18 | - name: Pack Router 19 | run: dotnet pack src/EdjCase.JsonRpc.Router/EdjCase.JsonRpc.Router.csproj --configuration Release /p:Version=${{ github.event.release.tag_name }} --output . --include-symbols --include-source 20 | 21 | - name: Push Router 22 | run: dotnet nuget push EdjCase.JsonRpc.Router.${{ github.event.release.tag_name }}.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json 23 | 24 | - name: Pack Client 25 | run: dotnet pack src/EdjCase.JsonRpc.Client/EdjCase.JsonRpc.Client.csproj --configuration Release /p:Version=${{ github.event.release.tag_name }} --output . --include-symbols --include-source 26 | 27 | - name: Push Client 28 | run: dotnet nuget push EdjCase.JsonRpc.Client.${{ github.event.release.tag_name }}.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json 29 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/EdjCase.JsonRpc.Router.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JsonRpc.Router.Tests Class Library 5 | Gekctek 6 | net6.0 7 | EdjCase.JsonRpc.Router.Tests 8 | EdjCase.JsonRpc.Router.Tests 9 | enable 10 | latest 11 | true 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | all 22 | runtime; build; native; contentfiles; analyzers 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router.Swagger/EdjCase.JsonRpc.Router.Swagger.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | An extension library for EdjCase.JsonRpc.Router to add Swagger functionality. 5 | 2m0nd;Gekctek 6 | net6.0 7 | EdjCase.JsonRpc.Router.Swagger 8 | EdjCase.JsonRpc.Router.Swagger 9 | JsonRpc Rpc AspNet Json-Rpc .Net Core Swagger 10 | Fixes to DI 11 | https://github.com/edjCase/JsonRpc 12 | MIT 13 | git 14 | https://github.com/edjCase/JsonRpc 15 | enable 16 | latest 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcRouterExceptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace EdjCase.JsonRpc.Router 7 | { 8 | 9 | /// 10 | /// Base exception for all rpc router exceptions 11 | /// 12 | public abstract class RpcRouterException : Exception 13 | { 14 | /// Error message 15 | protected RpcRouterException(string message, Exception? ex = null) : base(message, ex) 16 | { 17 | } 18 | } 19 | 20 | /// 21 | /// Exception for bad configuration of the Rpc server 22 | /// 23 | //Not a response exception so it is not an `RpcException` 24 | public class RpcConfigurationException : RpcRouterException 25 | { 26 | /// Error message 27 | public RpcConfigurationException(string message) : base(message) 28 | { 29 | } 30 | } 31 | /// 32 | /// Exception for a canceled rpc request 33 | /// 34 | //Not a response exception so it is not an `RpcException` 35 | public class RpcCanceledRequestException : RpcRouterException 36 | { 37 | /// Error message 38 | public RpcCanceledRequestException(string message, Exception? ex = null) : base(message, ex) 39 | { 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcBulkResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using EdjCase.JsonRpc.Common; 7 | 8 | namespace EdjCase.JsonRpc.Client 9 | { 10 | public class RpcBulkResponse 11 | { 12 | private IDictionary responses { get; } 13 | 14 | public RpcBulkResponse(IDictionary responses) 15 | { 16 | this.responses = responses ?? throw new ArgumentNullException(nameof(responses)); 17 | } 18 | 19 | public RpcResponse GetResponse(RpcId id) 20 | { 21 | return this.responses[id]; 22 | } 23 | 24 | public RpcResponse GetResponse(RpcId id) 25 | { 26 | return RpcResponse.FromResponse(this.responses[id]); 27 | } 28 | 29 | public List GetResponses() 30 | { 31 | return this.responses 32 | .Select(r => r.Value) 33 | .ToList(); 34 | } 35 | 36 | public List> GetResponses() 37 | { 38 | return this.responses 39 | .Select(r => RpcResponse.FromResponse(r.Value)) 40 | .ToList(); 41 | } 42 | 43 | internal static RpcBulkResponse FromResponses(List responses) 44 | { 45 | Dictionary responseMap = responses.ToDictionary(r => r.Id, r => r); 46 | return new RpcBulkResponse(responseMap); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/EdjCase.JsonRpc.Client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | A .Net Core Client implementation for Json Rpc v2 requests. 4 | Gekctek 5 | net6.0 6 | EdjCase.JsonRpc.Client 7 | EdjCase.JsonRpc.Client 8 | JsonRpc Rpc Json-Rpc .Net Core 9 | Integrated core project into client 10 | https://github.com/edjCase/JsonRpc 11 | MIT 12 | git 13 | enable 14 | latest 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcResponse.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using EdjCase.JsonRpc.Common; 3 | 4 | namespace EdjCase.JsonRpc.Router 5 | { 6 | public class RpcResponse 7 | { 8 | protected RpcResponse() 9 | { 10 | } 11 | 12 | /// Request id 13 | protected RpcResponse(RpcId id) 14 | { 15 | this.Id = id; 16 | } 17 | 18 | /// Request id 19 | /// Request error 20 | public RpcResponse(RpcId id, RpcError error) : this(id) 21 | { 22 | this.Error = error; 23 | } 24 | 25 | /// Request id 26 | /// Response result object 27 | public RpcResponse(RpcId id, object? result) : this(id) 28 | { 29 | this.Result = result; 30 | } 31 | 32 | /// 33 | /// Request id 34 | /// 35 | public RpcId Id { get; private set; } 36 | 37 | /// 38 | /// Reponse result object (Required) 39 | /// 40 | public object? Result { get; private set; } 41 | 42 | /// 43 | /// Error from processing Rpc request (Required) 44 | /// 45 | public RpcError? Error { get; private set; } 46 | 47 | public bool HasError => this.Error != null; 48 | 49 | public void ThrowErrorIfExists() 50 | { 51 | if (this.HasError) 52 | { 53 | throw this.Error!.CreateException(); 54 | } 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/Tools/StreamCompressors.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.IO.Compression; 5 | using System.Text; 6 | 7 | namespace EdjCase.JsonRpc.Common.Tools 8 | { 9 | internal interface IStreamCompressor 10 | { 11 | bool TryGetCompressionStream(Stream uncompressedStream, string encoding, CompressionMode mode, out Stream compressedStream); 12 | 13 | } 14 | 15 | internal class DefaultStreamCompressor : IStreamCompressor 16 | { 17 | 18 | /// 19 | /// Decompresses the input stream to the output stream. 20 | /// 21 | /// The uncompressed stream. 22 | /// Type of the compression. 23 | /// Specifies compression or decompression 24 | /// 25 | public bool TryGetCompressionStream(Stream uncompressedStream, string encoding, CompressionMode mode, out Stream compressedStream) 26 | { 27 | switch (encoding) 28 | { 29 | case "gzip": 30 | compressedStream = new GZipStream(uncompressedStream, mode, leaveOpen: false); 31 | return true; 32 | case "deflate": 33 | compressedStream = new DeflateStream(uncompressedStream, mode, leaveOpen: false); 34 | return true; 35 | default: 36 | compressedStream = uncompressedStream; 37 | return false; 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | // General Information about an assembly is controlled through the following 4 | // set of attributes. Change these attribute values to modify the information 5 | // associated with an assembly. 6 | // [assembly: AssemblyTitle("EdjCase.JsonRpc.Router.Properties")] 7 | // [assembly: AssemblyDescription("")] 8 | // [assembly: AssemblyConfiguration("")] 9 | // [assembly: AssemblyCompany("")] 10 | // [assembly: AssemblyProduct("EdjCase.JsonRpc.Router.Properties")] 11 | // [assembly: AssemblyCopyright("Copyright © 2020")] 12 | // [assembly: AssemblyTrademark("")] 13 | // [assembly: AssemblyCulture("")] 14 | 15 | // Setting ComVisible to false makes the types in this assembly not visible 16 | // to COM components. If you need to access a type in this assembly from 17 | // COM, set the ComVisible attribute to true on that type. 18 | // [assembly: ComVisible(false)] 19 | 20 | // The following GUID is for the ID of the typelib if this project is exposed to COM 21 | // [assembly: Guid("27dbfb84-2e0e-4d81-a172-fbc8c8ab44d4")] 22 | 23 | // Version information for an assembly consists of the following four values: 24 | // 25 | // Major Version 26 | // Minor Version 27 | // Build Number 28 | // Revision 29 | // 30 | // [assembly: AssemblyVersion("1.0.0.0")] 31 | // [assembly: AssemblyFileVersion("1.0.0.0")] 32 | [assembly: InternalsVisibleTo("EdjCase.JsonRpc.Client.Tests")] 33 | [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] 34 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcEvents.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.IO.Compression; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using EdjCase.JsonRpc.Common; 8 | using Newtonsoft.Json; 9 | using Newtonsoft.Json.Linq; 10 | using System.Net.Http; 11 | using System.Net.Http.Headers; 12 | using System.Text; 13 | using EdjCase.JsonRpc.Common.Tools; 14 | 15 | namespace EdjCase.JsonRpc.Client 16 | { 17 | public class RpcEvents 18 | { 19 | public Func? OnRequestStartAsync { get; set; } 20 | public Func? OnRequestCompleteAsync { get; set; } 21 | } 22 | 23 | public class RequestEventContext 24 | { 25 | public string? Route { get; } 26 | public List Requests { get; } 27 | public string RequestJson { get; } 28 | 29 | public RequestEventContext(string? route, List requests, string requestJson) 30 | { 31 | this.Route = route; 32 | this.Requests = requests; 33 | this.RequestJson = requestJson; 34 | } 35 | } 36 | 37 | public class ResponseEventContext 38 | { 39 | public string ResponseJson { get; } 40 | public List? Responses { get; } 41 | public Exception? ClientError { get; } 42 | 43 | public ResponseEventContext(string responseJson, List? responses, Exception? clientError = null) 44 | { 45 | this.ResponseJson = responseJson; 46 | this.Responses = responses; 47 | this.ClientError = clientError; 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /test/Benchmarks/BasicTests.websurge: -------------------------------------------------------------------------------- 1 | POST http://localhost:5000/Test HTTP/1.1 2 | Accept-Encoding: gzip,deflate 3 | Websurge-Request-Name: RPC 4 | 5 | {"id": "6e5fd5f5-d8b2-486c-a6ef-3800dd56a857", "jsonrpc": "2.0", "method": "Ping", "params": []} 6 | 7 | ------------------------------------------------------------------ 8 | 9 | POST http://localhost:5000/Test HTTP/1.1 10 | Websurge-Request-Name: RPC No Compression 11 | 12 | {"id": "6e5fd5f5-d8b2-486c-a6ef-3800dd56a857", "jsonrpc": "2.0", "method": "Ping", "params": []} 13 | 14 | ------------------------------------------------------------------ 15 | 16 | 17 | ----- Start WebSurge Options ----- 18 | 19 | { 20 | "NoProgressEvents": true, 21 | "DelayTimeMs": 0, 22 | "NoContentDecompression": false, 23 | "CaptureMinimalResponseData": false, 24 | "MaxResponseSize": 0, 25 | "ReplaceQueryStringValuePairs": null, 26 | "ReplaceDomain": null, 27 | "ReplaceCookieValue": null, 28 | "ReplaceAuthorization": null, 29 | "Username": null, 30 | "Password": null, 31 | "Users": [], 32 | "RandomizeRequests": false, 33 | "RequestTimeoutMs": 15000, 34 | "WarmupSeconds": 2, 35 | "ReloadTemplates": false, 36 | "FormattedPreviewTheme": "visualstudio", 37 | "LastThreads": 12, 38 | "IgnoreCertificateErrors": false, 39 | "TrackPerSessionCookies": true, 40 | "LastSecondsToRun": 10 41 | } 42 | 43 | // This file was generated by West Wind WebSurge 44 | // Get your free copy at http://websurge.west-wind.com 45 | // to easily test or load test the requests in this file. 46 | 47 | ----- End WebSurge Options ----- 48 | 49 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | // General Information about an assembly is controlled through the following 4 | // set of attributes. Change these attribute values to modify the information 5 | // associated with an assembly. 6 | // [assembly: AssemblyTitle("EdjCase.JsonRpc.Router.Properties")] 7 | // [assembly: AssemblyDescription("")] 8 | // [assembly: AssemblyConfiguration("")] 9 | // [assembly: AssemblyCompany("")] 10 | // [assembly: AssemblyProduct("EdjCase.JsonRpc.Router.Properties")] 11 | // [assembly: AssemblyCopyright("Copyright © 2020")] 12 | // [assembly: AssemblyTrademark("")] 13 | // [assembly: AssemblyCulture("")] 14 | 15 | // Setting ComVisible to false makes the types in this assembly not visible 16 | // to COM components. If you need to access a type in this assembly from 17 | // COM, set the ComVisible attribute to true on that type. 18 | // [assembly: ComVisible(false)] 19 | 20 | // The following GUID is for the ID of the typelib if this project is exposed to COM 21 | // [assembly: Guid("27dbfb84-2e0e-4d81-a172-fbc8c8ab44d4")] 22 | 23 | // Version information for an assembly consists of the following four values: 24 | // 25 | // Major Version 26 | // Minor Version 27 | // Build Number 28 | // Revision 29 | // 30 | // [assembly: AssemblyVersion("1.0.0.0")] 31 | // [assembly: AssemblyFileVersion("1.0.0.0")] 32 | [assembly: InternalsVisibleTo("EdjCase.JsonRpc.Router.Tests")] 33 | [assembly: InternalsVisibleTo("Benchmarks")] 34 | //For Mocking an internal type 35 | [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] 36 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Utilities/RpcUtil.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common.Utilities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | 7 | namespace EdjCase.JsonRpc.Router.Utilities 8 | { 9 | internal class RpcUtil 10 | { 11 | public static bool TypesMatch(object value, Type type) 12 | { 13 | Type? nullableType = Nullable.GetUnderlyingType(type); 14 | if (nullableType != null) 15 | { 16 | type = nullableType; 17 | } 18 | return value?.GetType() == type; 19 | } 20 | 21 | public static bool NamesMatch(ReadOnlySpan actual, ReadOnlySpan requested) 22 | { 23 | //Requested can be longer because it could have - or _ characters 24 | if (actual.Length > requested.Length) 25 | { 26 | return false; 27 | } 28 | int j = 0; 29 | int equalsChars = 0; 30 | for (int i = 0; i < actual.Length && j < requested.Length; i++) 31 | { 32 | char requestedChar = requested[j++]; 33 | char actualChar = actual[i]; 34 | if (char.ToLowerInvariant(actualChar) == char.ToLowerInvariant(requestedChar)) 35 | { 36 | equalsChars++; 37 | continue; 38 | } 39 | if (requestedChar == '-' || requestedChar == '_') 40 | { 41 | //Skip this j 42 | i--; 43 | continue; 44 | } 45 | return false; 46 | } 47 | //Make sure that it matched ALL the actual characters 48 | //j - all iterations of comparing, need compare j with requested.Length 49 | return j == requested.Length 50 | && equalsChars == actual.Length; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/EdjCase.JsonRpc.Router.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A AspNet Core IRouter implementation for Json Rpc v2 requests for Microsoft.AspNetCore.Routing. 5 | Gekctek 6 | net6.0 7 | EdjCase.JsonRpc.Router 8 | EdjCase.JsonRpc.Router 9 | JsonRpc Rpc AspNet Json-Rpc .Net Core 10 | Fixing Optional parameter matching issue 11 | https://github.com/edjCase/JsonRpc 12 | MIT 13 | git 14 | https://github.com/edjCase/JsonRpc 15 | enable 16 | latest 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcBulkRequest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using EdjCase.JsonRpc.Common; 7 | 8 | namespace EdjCase.JsonRpc.Client 9 | { 10 | public class RpcBulkRequest 11 | { 12 | private IList<(RpcRequest Request, Type ResponseType)> requests { get; } 13 | public RpcBulkRequest(IList<(RpcRequest, Type)> requests) 14 | { 15 | if(requests == null) 16 | { 17 | throw new ArgumentNullException(nameof(requests)); 18 | } 19 | if (!requests.Any()) 20 | { 21 | throw new ArgumentException("Need at least one request", nameof(requests)); 22 | } 23 | this.requests = requests; 24 | } 25 | 26 | public static RpcBulkRequest FromRequests(List requests, IDictionary responseTypeMap) 27 | { 28 | List<(RpcRequest Request, Type ResponseType)> list = requests 29 | .Select(r => (r, responseTypeMap[r.Id])) 30 | .ToList(); 31 | return new RpcBulkRequest(list); 32 | } 33 | 34 | public static RpcBulkRequest FromRequests(List requests) 35 | { 36 | Type responseType = typeof(TResponseType); 37 | List<(RpcRequest Request, Type ResponseType)> list = requests 38 | .Select(r => (r, responseType)) 39 | .ToList(); 40 | return new RpcBulkRequest(list); 41 | } 42 | 43 | internal IDictionary GetTypeMap() 44 | { 45 | return this.requests.ToDictionary(r => r.Request.Id, r => r.ResponseType); 46 | } 47 | 48 | internal List GetRequests() 49 | { 50 | return this.requests 51 | .Select(r => r.Request) 52 | .ToList(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/Controllers/MethodMatcherController.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router.Abstractions; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace EdjCase.JsonRpc.Router.Tests.Controllers 6 | { 7 | public class MethodMatcherController : RpcController 8 | { 9 | public Guid GuidTypeMethod(Guid guid) 10 | { 11 | return guid; 12 | } 13 | 14 | public (int, bool, string, object, int?) SimpleMulitParam(int a, bool b, string c, object d, int? e = null) 15 | { 16 | return (a, b, c, d, e); 17 | } 18 | 19 | public List List(List values) 20 | { 21 | return values; 22 | } 23 | 24 | public string SnakeCaseParams(string parameterOne) 25 | { 26 | return parameterOne; 27 | } 28 | 29 | public bool IsLunchTime() 30 | { 31 | return true; 32 | } 33 | 34 | public (string, string?) Optional(string required, string? optional = null) 35 | { 36 | return (required, optional); 37 | } 38 | 39 | // https://github.com/edjCase/JsonRpc/issues/99 40 | public IRpcMethodResult CreateInfoHelperItem(string name, string language, string value, string description, string component, string locationIndex, string fontFamily = "Arial", int fontSize = 12, bool bold = false, bool italic = false, bool strikeout = false, bool underline = false) 41 | { 42 | return this.Ok((name, language, value, description, component, locationIndex, fontFamily, fontSize, bold, italic, strikeout, underline)); ; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Build Client Sample", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/test/EdjCase.JsonRpc.Router.Sample/EdjCase.JsonRpc.Router.Sample.csproj", 11 | "/property:GenerateFullPaths=true" 12 | ], 13 | "problemMatcher": "$msCompile" 14 | }, 15 | { 16 | "label": "Build Router Sample", 17 | "command": "dotnet", 18 | "type": "process", 19 | "args": [ 20 | "build", 21 | "${workspaceFolder}/test/EdjCase.JsonRpc.Router.Sample/EdjCase.JsonRpc.Router.Sample.csproj", 22 | "/property:GenerateFullPaths=true" 23 | ], 24 | "problemMatcher": "$msCompile" 25 | }, 26 | { 27 | "label": "Build Performance Tests", 28 | "command": "dotnet", 29 | "type": "process", 30 | "args": [ 31 | "build", 32 | "${workspaceFolder}/test/PerformanceTests/PerformanceTests.csproj", 33 | "/property:GenerateFullPaths=true" 34 | ], 35 | "problemMatcher": "$msCompile" 36 | }, 37 | { 38 | "label": "Build All", 39 | "command": "dotnet", 40 | "type": "process", 41 | "args": [ 42 | "build", 43 | "${workspaceFolder}/EdjCase.JsonRpc.sln", 44 | "/property:GenerateFullPaths=true" 45 | ], 46 | "problemMatcher": "$msCompile", 47 | "group": { 48 | "kind": "build", 49 | "isDefault": true 50 | } 51 | }, 52 | { 53 | "label": "Test All", 54 | "command": "dotnet", 55 | "type": "process", 56 | "args": [ 57 | "test", 58 | "${workspaceFolder}/test/EdjCase.JsonRpc.Router.Tests" 59 | ], 60 | "problemMatcher": "$msCompile", 61 | "group": { 62 | "kind": "test", 63 | "isDefault": true 64 | } 65 | } 66 | ] 67 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/RpcExceptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EdjCase.JsonRpc.Common 4 | { 5 | /// 6 | /// Rpc server exception that contains Rpc specfic error info 7 | /// 8 | public class RpcException : Exception 9 | { 10 | /// 11 | /// Rpc error code that corresponds to the documented integer codes 12 | /// 13 | public int ErrorCode { get; } 14 | /// 15 | /// Custom data attached to the error if needed 16 | /// 17 | public object? RpcData { get; } 18 | 19 | /// Rpc error code 20 | /// Error message 21 | /// Custom data if needed for error response 22 | /// Inner exception (optional) 23 | public RpcException(int errorCode, string message, Exception? innerException = null, object? data = null) 24 | : base(message, innerException) 25 | { 26 | this.ErrorCode = errorCode; 27 | this.RpcData = data; 28 | } 29 | /// Rpc error code 30 | /// Error message 31 | /// Custom data if needed for error response 32 | /// Inner exception (optional) 33 | public RpcException(RpcErrorCode errorCode, string message, Exception? innerException = null, object? data = null) 34 | : this((int)errorCode, message, innerException, data) 35 | { 36 | } 37 | 38 | public RpcError ToRpcError(bool includeServerErrors) 39 | { 40 | string message = this.Message; 41 | if (includeServerErrors) 42 | { 43 | message += Environment.NewLine + "Exception: " + this.InnerException; 44 | } 45 | return new RpcError(this.ErrorCode, message, this.RpcData); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcMethodProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Text; 5 | using Microsoft.AspNetCore.Authorization; 6 | 7 | namespace EdjCase.JsonRpc.Router.Abstractions 8 | { 9 | public interface IRpcMethodProvider 10 | { 11 | RpcRouteMetaData Get(); 12 | } 13 | 14 | 15 | public class RpcRouteMetaData 16 | { 17 | public IReadOnlyList BaseRoute { get; } 18 | public IReadOnlyDictionary> PathRoutes { get; } 19 | 20 | public RpcRouteMetaData(IReadOnlyList baseMethods, IReadOnlyDictionary> methods) 21 | { 22 | this.BaseRoute = baseMethods; 23 | this.PathRoutes = methods; 24 | } 25 | } 26 | 27 | public interface IRpcMethodInfo 28 | { 29 | string Name { get; } 30 | IReadOnlyList Parameters { get; } 31 | bool AllowAnonymous { get; } 32 | IReadOnlyList AuthorizeDataList { get; } 33 | Type RawReturnType { get; } 34 | 35 | object? Invoke(object[] parameters, IServiceProvider serviceProvider); 36 | } 37 | 38 | public interface IRpcParameterInfo 39 | { 40 | string Name { get; } 41 | Type RawType { get; } 42 | bool IsOptional { get; } 43 | } 44 | 45 | public static class MethodProviderExtensions 46 | { 47 | public static IReadOnlyList? GetByPath(this IRpcMethodProvider methodProvider, RpcPath? path) 48 | { 49 | RpcRouteMetaData metaData = methodProvider.Get(); 50 | if (path == null) 51 | { 52 | return metaData.BaseRoute; 53 | } 54 | if (metaData.PathRoutes.TryGetValue(path, out IReadOnlyList? methods)) 55 | { 56 | return methods; 57 | } 58 | return null; 59 | } 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/RpcError.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EdjCase.JsonRpc.Common 4 | { 5 | public class RpcError : RpcError 6 | { 7 | public RpcError(RpcErrorCode code, string message, T data) 8 | : base(code, message, data) 9 | { 10 | } 11 | 12 | public RpcError(int code, string message, T data) 13 | : base(code, message, data) 14 | { 15 | } 16 | 17 | public new T Data => (T)base.Data!; 18 | } 19 | 20 | /// 21 | /// Model to represent an Rpc response error 22 | /// 23 | public class RpcError 24 | { 25 | 26 | /// Rpc error code 27 | /// Error message 28 | /// Optional error data 29 | public RpcError(RpcErrorCode code, string message, object? data = null) 30 | : this((int)code, message, data) 31 | { 32 | } 33 | 34 | /// Rpc error code 35 | /// Error message 36 | /// Optional error data 37 | public RpcError(int code, string message, object? data = null) 38 | { 39 | if (string.IsNullOrWhiteSpace(message)) 40 | { 41 | throw new ArgumentNullException(nameof(message)); 42 | } 43 | this.Code = code; 44 | this.Message = message; 45 | this.Data = data; 46 | this.DataType = data?.GetType(); 47 | } 48 | 49 | /// 50 | /// Rpc error code (Required) 51 | /// 52 | public int Code { get; } 53 | 54 | public string Message { get; } 55 | 56 | /// 57 | /// Error data (Optional) 58 | /// 59 | public object? Data { get; } 60 | 61 | /// 62 | /// Type of the data object 63 | /// 64 | public Type? DataType { get; } 65 | 66 | public RpcException CreateException() 67 | { 68 | return new RpcException(this.Code, this.Message, data: this.Data); 69 | } 70 | 71 | } 72 | } -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/RpcUtilTests.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Router.Defaults; 3 | using Microsoft.Extensions.Options; 4 | using EdjCase.JsonRpc.Router.Abstractions; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Text; 9 | using Xunit; 10 | using System.Threading.Tasks; 11 | using EdjCase.JsonRpc.Router.Utilities; 12 | 13 | namespace EdjCase.JsonRpc.Router.Tests 14 | { 15 | public class RpcUtilTests 16 | { 17 | [Theory] 18 | [InlineData("TestCase", "testcase")] 19 | [InlineData("TestCase", "test_case")] 20 | [InlineData("TestCase", "TEST_CASE")] 21 | [InlineData("TestCase", "test-case")] 22 | [InlineData("TestCase", "TEST-CASE")] 23 | [InlineData("test", "Test")] 24 | public void MatchMethodNamesTest(string methodInfo, string requestMethodName) 25 | { 26 | Assert.True(RpcUtil.NamesMatch(methodInfo, requestMethodName)); 27 | } 28 | 29 | [Theory] 30 | [InlineData("GetUsers", "get_user")] 31 | [InlineData("GetUsers", "get_user_super")] 32 | public void NotMatchMethodNamesTest(string methodInfo, string requestMethodName) 33 | { 34 | Assert.False(RpcUtil.NamesMatch(methodInfo, requestMethodName)); 35 | } 36 | 37 | [Fact] 38 | public void MatchMethodNamesCulturallyInvariantTest() 39 | { 40 | var previousCulture = System.Globalization.CultureInfo.CurrentCulture; 41 | // Switch to a locale that would result in lowercasing 'I' to 42 | // U+0131, if not done with invariant culture. 43 | System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("az"); 44 | var methodInfo = "IsLunchTime"; 45 | var requestMethodName = "isLunchtIme"; 46 | Assert.True(RpcUtil.NamesMatch(methodInfo, requestMethodName)); 47 | System.Globalization.CultureInfo.CurrentCulture = previousCulture; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/Controllers/ComplexExampleController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace EdjCase.JsonRpc.Router.Sample.Controllers 8 | { 9 | /// 10 | /// This complex api 11 | /// 12 | [RpcRoute("api/v1/complex")] 13 | public class ComplexExampleController : ControllerBase 14 | { 15 | static ConcurrentDictionary memoryCache = new ConcurrentDictionary(); 16 | 17 | 18 | /// 19 | /// Save or update model 20 | /// 21 | /// 22 | /// 23 | public async Task Save(ComplexInputModel model) 24 | { 25 | await Task.Run(() => 26 | { 27 | memoryCache.AddOrUpdate(model.Id, model, (i, inputModel) => 28 | { 29 | inputModel.Title = model.Title; 30 | inputModel.CreatedOn = model.CreatedOn; 31 | inputModel.IsEnabled = model.IsEnabled; 32 | 33 | return inputModel; 34 | }); 35 | }); 36 | } 37 | 38 | 39 | /// 40 | /// Get model by id 41 | /// 42 | /// 43 | /// 44 | public async Task Get(int id) 45 | { 46 | return await Task.Run(() => 47 | { 48 | memoryCache.TryGetValue(id, out var model); 49 | return model; 50 | }); 51 | } 52 | 53 | 54 | /// 55 | /// Get all models 56 | /// 57 | /// 58 | public async Task> Get() 59 | { 60 | return await Task.Run(() => memoryCache.Select(x => x.Value)); 61 | } 62 | } 63 | 64 | public class ComplexInputModel 65 | { 66 | public int Id { get; set; } 67 | public string Title { get; set; } 68 | public bool IsEnabled { get; set; } 69 | public DateTime CreatedOn { get; set; } 70 | } 71 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcRequest.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Router.Utilities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.ComponentModel; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Text.Json; 9 | 10 | namespace EdjCase.JsonRpc.Router 11 | { 12 | public class RpcRequest 13 | { 14 | public RpcId Id { get; } 15 | public string Method { get; } 16 | public TopLevelRpcParameters? Parameters { get; } 17 | public RpcRequest(RpcId id, string method, TopLevelRpcParameters? parameters = null) 18 | { 19 | this.Id = id; 20 | this.Method = method; 21 | this.Parameters = parameters; 22 | } 23 | } 24 | 25 | public class TopLevelRpcParameters 26 | { 27 | public object Value { get; } 28 | public bool IsDictionary { get; } 29 | 30 | public TopLevelRpcParameters(Dictionary parameters) 31 | { 32 | this.Value = parameters ?? throw new ArgumentNullException(nameof(parameters)); 33 | this.IsDictionary = true; 34 | } 35 | 36 | public TopLevelRpcParameters(params RpcParameter[] parameters) 37 | { 38 | this.Value = parameters ?? throw new ArgumentNullException(nameof(parameters)); 39 | this.IsDictionary = false; 40 | } 41 | 42 | public Dictionary AsDictionary 43 | { 44 | get 45 | { 46 | this.CheckValue(isDictionary: true); 47 | return (Dictionary)this.Value; 48 | } 49 | } 50 | 51 | public RpcParameter[] AsArray 52 | { 53 | get 54 | { 55 | this.CheckValue(isDictionary: false); 56 | return (RpcParameter[])this.Value; 57 | } 58 | } 59 | 60 | private void CheckValue(bool isDictionary) 61 | { 62 | if (isDictionary != this.IsDictionary) 63 | { 64 | throw new InvalidOperationException(); 65 | } 66 | } 67 | 68 | public bool Any() 69 | { 70 | if (this.IsDictionary) 71 | { 72 | return this.AsDictionary.Any(); 73 | } 74 | return this.AsArray.Any(); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using EdjCase.JsonRpc.Common; 3 | 4 | // ReSharper disable AutoPropertyCanBeMadeGetOnly.Local 5 | // ReSharper disable UnusedMember.Local 6 | 7 | namespace EdjCase.JsonRpc.Client 8 | { 9 | public class RpcResponse : RpcResponse 10 | { 11 | public RpcResponse(RpcId id, T result) 12 | : base(id, result) 13 | { 14 | 15 | } 16 | 17 | public RpcResponse(RpcId id, RpcError error) 18 | : base(id, error) 19 | { 20 | 21 | } 22 | 23 | public new T Result => (T)base.Result!; 24 | 25 | 26 | public static RpcResponse FromResponse(RpcResponse response) 27 | { 28 | if (response.HasError) 29 | { 30 | return new RpcResponse(response.Id, response.Error!); 31 | } 32 | return new RpcResponse(response.Id, (T)response.Result!); 33 | } 34 | } 35 | 36 | public class RpcResponse 37 | { 38 | protected RpcResponse() 39 | { 40 | this.Id = new RpcId(); 41 | } 42 | 43 | /// Request id 44 | protected RpcResponse(RpcId id) 45 | { 46 | this.Id = id; 47 | } 48 | 49 | /// Request id 50 | /// Request error 51 | public RpcResponse(RpcId id, RpcError error) : this(id) 52 | { 53 | this.Error = error; 54 | } 55 | 56 | /// Request id 57 | /// Response result object 58 | public RpcResponse(RpcId id, object? result) : this(id) 59 | { 60 | this.Result = result; 61 | } 62 | 63 | /// 64 | /// Request id 65 | /// 66 | public RpcId Id { get; private set; } 67 | 68 | /// 69 | /// Reponse result object (Required) 70 | /// 71 | public object? Result { get; private set; } 72 | 73 | /// 74 | /// Error from processing Rpc request (Required) 75 | /// 76 | public RpcError? Error { get; private set; } 77 | 78 | public bool HasError => this.Error != null; 79 | 80 | public void ThrowErrorIfExists() 81 | { 82 | if (this.HasError) 83 | { 84 | throw this.Error!.CreateException(); 85 | } 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcController.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router.Abstractions; 2 | using EdjCase.JsonRpc.Router.Defaults; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace EdjCase.JsonRpc.Router 9 | { 10 | public abstract class RpcController 11 | { 12 | /// 13 | /// Helper for returning a successful rpc response 14 | /// 15 | /// Object to return in response 16 | /// Success result for rpc response 17 | [NonRpcMethod] 18 | protected virtual RpcMethodSuccessResult Ok(object? obj = null) 19 | { 20 | return new RpcMethodSuccessResult(obj); 21 | } 22 | 23 | 24 | /// 25 | /// Helper for returning an error rpc response 26 | /// 27 | /// JSON-RPC custom error code 28 | /// (Optional)Error message 29 | /// (Optional)Error data 30 | /// 31 | [NonRpcMethod] 32 | protected virtual RpcMethodErrorResult Error(int errorCode, string message, object? data = null) 33 | { 34 | return new RpcMethodErrorResult(errorCode, message, data); 35 | } 36 | } 37 | 38 | /// 39 | /// Attribute to decorate a derived class 40 | /// Allows setting a custom route name instead of using the controller name 41 | /// 42 | public class RpcRouteAttribute : Attribute 43 | { 44 | /// 45 | /// Name of the route to be used in the router. If unspecified, will use controller name. 46 | /// 47 | public string? RouteName { get; } 48 | 49 | /// 50 | /// 51 | /// 52 | /// (Optional) Name of the route to be used in the router. If unspecified, will use controller name. 53 | public RpcRouteAttribute(string? routeName) 54 | { 55 | this.RouteName = routeName; 56 | } 57 | } 58 | 59 | /// 60 | /// Attribute to decorate a method from a derived class 61 | /// Allows a method to not be included as a method 62 | /// 63 | public class NonRpcMethodAttribute : Attribute 64 | { 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EdjCase.JsonRpc.Router 4 | { 5 | public class RpcNumber 6 | { 7 | private readonly string stringValue; 8 | public RpcNumber(string stringValue) 9 | { 10 | this.stringValue = stringValue ?? throw new ArgumentNullException(nameof(stringValue)); 11 | } 12 | 13 | public override string ToString() 14 | { 15 | return this.stringValue; 16 | } 17 | 18 | public static implicit operator RpcNumber(short d) => new RpcNumber(d.ToString()); 19 | public bool TryGetShort(out short v) 20 | { 21 | return short.TryParse(this.stringValue, out v); 22 | } 23 | public static implicit operator RpcNumber(ushort d) => new RpcNumber(d.ToString()); 24 | public bool TryGetUnsignedShort(out ushort v) 25 | { 26 | return ushort.TryParse(this.stringValue, out v); 27 | } 28 | public static implicit operator RpcNumber(int d) => new RpcNumber(d.ToString()); 29 | public bool TryGetInteger(out int v) 30 | { 31 | return int.TryParse(this.stringValue, out v); 32 | } 33 | public static implicit operator RpcNumber(uint d) => new RpcNumber(d.ToString()); 34 | public bool TryGetUnsignedInteger(out uint v) 35 | { 36 | return uint.TryParse(this.stringValue, out v); 37 | } 38 | public static implicit operator RpcNumber(long d) => new RpcNumber(d.ToString()); 39 | public bool TryGetLong(out long v) 40 | { 41 | return long.TryParse(this.stringValue, out v); 42 | } 43 | public static implicit operator RpcNumber(ulong d) => new RpcNumber(d.ToString()); 44 | public bool TryGetUnsingedLong(out ulong v) 45 | { 46 | return ulong.TryParse(this.stringValue, out v); 47 | } 48 | public static implicit operator RpcNumber(float d) => new RpcNumber(d.ToString()); 49 | public bool TryGetFloat(out float v) 50 | { 51 | return float.TryParse(this.stringValue, out v); 52 | } 53 | public static implicit operator RpcNumber(double d) => new RpcNumber(d.ToString()); 54 | public bool TryGetDouble(out double v) 55 | { 56 | return double.TryParse(this.stringValue, out v); 57 | } 58 | public static implicit operator RpcNumber(decimal d) => new RpcNumber(d.ToString()); 59 | public bool TryGetDecimal(out decimal v) 60 | { 61 | return decimal.TryParse(this.stringValue, out v); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Router Tester", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "Build Router Sample", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/test/EdjCase.JsonRpc.Router.Sample/bin/Debug/netcoreapp3.0/EdjCase.JsonRpc.Router.Sample.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/test/EdjCase.JsonRpc.Router.Sample", 16 | // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window 17 | "console": "internalConsole", 18 | "stopAtEntry": false, 19 | "internalConsoleOptions": "openOnSessionStart" 20 | }, 21 | { 22 | "name": "Performance Tests", 23 | "type": "coreclr", 24 | "request": "launch", 25 | "preLaunchTask": "Build Performance Tests", 26 | // If you have changed target frameworks, make sure to update the program path. 27 | "program": "${workspaceFolder}/test/PerformanceTests/bin/Debug/netcoreapp3.0/PerformanceTests.dll", 28 | "args": [], 29 | "cwd": "${workspaceFolder}/test/PerformanceTests", 30 | // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window 31 | "console": "internalConsole", 32 | "stopAtEntry": false, 33 | "internalConsoleOptions": "openOnSessionStart" 34 | }, 35 | { 36 | "name": "Client Tester", 37 | "type": "coreclr", 38 | "request": "launch", 39 | "preLaunchTask": "Build Client Sample", 40 | "program": "${workspaceRoot}/test/Edjcase.JsonRpc.Client.Sample/bin/Debug/netcoreapp3.0/EdjCase.JsonRpc.Client.Sample.dll", 41 | "args": [], 42 | "cwd": "${workspaceRoot}", 43 | "stopAtEntry": false, 44 | "console": "internalConsole" 45 | }, 46 | { 47 | "name": ".NET Core Attach", 48 | "type": "coreclr", 49 | "request": "attach", 50 | "processId": "${command:pickProcess}" 51 | } 52 | ] 53 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcParameters.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace EdjCase.JsonRpc.Client 7 | { 8 | public enum RpcParametersType 9 | { 10 | Array, 11 | Dictionary 12 | } 13 | 14 | public struct RpcParameters 15 | { 16 | public bool HasValue { get; } 17 | 18 | public RpcParametersType Type { get; } 19 | 20 | public object Value { get; } 21 | 22 | public Dictionary DictionaryValue 23 | { 24 | get 25 | { 26 | if (this.Type != RpcParametersType.Dictionary) 27 | { 28 | throw new InvalidOperationException("Cannot cast params to dictionary."); 29 | } 30 | return (Dictionary)this.Value; 31 | } 32 | } 33 | 34 | public object[] ArrayValue 35 | { 36 | get 37 | { 38 | if (this.Type != RpcParametersType.Array) 39 | { 40 | throw new InvalidOperationException("Cannot cast params to array."); 41 | } 42 | return (object[])this.Value; 43 | } 44 | } 45 | 46 | public RpcParameters(object[]? parameters) 47 | { 48 | this.HasValue = true; 49 | this.Type = RpcParametersType.Array; 50 | this.Value = parameters ?? new object[0]; 51 | } 52 | 53 | public RpcParameters(Dictionary? parameters) 54 | { 55 | this.HasValue = true; 56 | this.Type = RpcParametersType.Dictionary; 57 | this.Value = parameters ?? new Dictionary(); 58 | } 59 | 60 | public static RpcParameters Empty => new RpcParameters(new object[0]); 61 | 62 | public static RpcParameters FromList(IEnumerable parameters) 63 | { 64 | return new RpcParameters(parameters?.ToArray()); 65 | } 66 | 67 | public static RpcParameters From(params object[] parameters) 68 | { 69 | return new RpcParameters(parameters); 70 | } 71 | 72 | public static RpcParameters FromDictionary(IDictionary parameters) 73 | { 74 | return new RpcParameters(parameters?.ToDictionary(kv => kv.Key, kv => kv.Value)); 75 | } 76 | 77 | public static implicit operator RpcParameters(List parameters) 78 | { 79 | return new RpcParameters(parameters?.ToArray()); 80 | } 81 | 82 | 83 | public static implicit operator RpcParameters(object[] parameters) 84 | { 85 | return new RpcParameters(parameters); 86 | } 87 | 88 | public static implicit operator RpcParameters(Dictionary parameters) 89 | { 90 | return new RpcParameters(parameters); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Defaults/DefaultRpcMethodResults.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Router.Abstractions; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace EdjCase.JsonRpc.Router.Defaults 9 | { 10 | /// 11 | /// Error result for rpc responses 12 | /// 13 | public class RpcMethodErrorResult : IRpcMethodResult 14 | { 15 | /// 16 | /// Error message 17 | /// 18 | public string Message { get; } 19 | /// 20 | /// JSON-RPC error code 21 | /// 22 | public int ErrorCode { get; } 23 | 24 | /// 25 | /// Data for error response 26 | /// 27 | public object? Data { get; } 28 | 29 | /// JSON-RPC error code 30 | /// (Optional)Error message 31 | /// (Optional)Data for error response 32 | public RpcMethodErrorResult(int errorCode, string message, object? data = null) 33 | { 34 | this.ErrorCode = errorCode; 35 | this.Message = message; 36 | this.Data = data; 37 | } 38 | 39 | /// 40 | /// Turns result data into a rpc response 41 | /// 42 | /// Rpc request id 43 | /// Json serializer function to use for objects for the response 44 | /// Rpc response for request 45 | public RpcResponse ToRpcResponse(RpcId id) 46 | { 47 | RpcError error = new RpcError(this.ErrorCode, this.Message, this.Data); 48 | return new RpcResponse(id, error); 49 | } 50 | } 51 | 52 | /// 53 | /// Success result for rpc responses 54 | /// 55 | public class RpcMethodSuccessResult : IRpcMethodResult 56 | { 57 | /// 58 | /// Object to return in rpc response 59 | /// 60 | public object? ReturnObject { get; } 61 | /// 62 | /// 63 | /// 64 | /// Object to return in rpc response 65 | public RpcMethodSuccessResult(object? returnObject = null) 66 | { 67 | this.ReturnObject = returnObject; 68 | } 69 | 70 | /// 71 | /// Turns result data into a rpc response 72 | /// 73 | /// Rpc request id 74 | /// Json serializer function to use for objects for the response 75 | /// Rpc response for request 76 | public RpcResponse ToRpcResponse(RpcId id) 77 | { 78 | return new RpcResponse(id, this.ReturnObject); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcClientExceptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using EdjCase.JsonRpc.Common; 3 | 4 | namespace EdjCase.JsonRpc.Client 5 | { 6 | /// 7 | /// Base exception that is thrown from an error that was caused by the client 8 | /// for the rpc request (not caused by rpc server) 9 | /// 10 | public abstract class RpcClientException : Exception 11 | { 12 | /// Error message 13 | protected RpcClientException(string message) : base(message) 14 | { 15 | 16 | } 17 | 18 | /// Error message 19 | /// Inner exception 20 | protected RpcClientException(string message, Exception innerException) : base(message, innerException) 21 | { 22 | 23 | } 24 | } 25 | 26 | /// 27 | /// Exception for all unknown exceptions that were thrown by the client 28 | /// 29 | public class RpcClientUnknownException : RpcClientException 30 | { 31 | /// Error message 32 | public RpcClientUnknownException(string message) : base(message) 33 | { 34 | } 35 | 36 | /// Error message 37 | /// Inner exception 38 | public RpcClientUnknownException(string message, Exception innerException) : base(message, innerException) 39 | { 40 | } 41 | } 42 | 43 | /// 44 | /// Exception for all parsing exceptions that were thrown by the client 45 | /// 46 | public class RpcClientParseException : RpcClientException 47 | { 48 | /// Error message 49 | public RpcClientParseException(string message) : base(message) 50 | { 51 | } 52 | 53 | /// Error message 54 | /// Inner exception 55 | public RpcClientParseException(string message, Exception innerException) : base(message, innerException) 56 | { 57 | } 58 | } 59 | 60 | /// 61 | /// Exception for all bad http status codes that were thrown by the client 62 | /// 63 | public class RpcClientInvalidStatusCodeException : RpcClientException 64 | { 65 | public System.Net.HttpStatusCode StatusCode { get; } 66 | public string Content { get; } 67 | 68 | /// Http Status Code 69 | /// Inner exception 70 | public RpcClientInvalidStatusCodeException(System.Net.HttpStatusCode statusCode, string content) 71 | : base($"The server returned an invalid status code of '{statusCode}'. Response content: {content}.") 72 | { 73 | this.StatusCode = statusCode; 74 | this.Content = content; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcRequest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System; 4 | using EdjCase.JsonRpc.Common; 5 | 6 | // ReSharper disable AutoPropertyCanBeMadeGetOnly.Local 7 | // ReSharper disable UnusedMember.Local 8 | 9 | namespace EdjCase.JsonRpc.Client 10 | { 11 | /// 12 | /// Model representing a Rpc request 13 | /// 14 | public class RpcRequest 15 | { 16 | /// Request id 17 | /// Target method name 18 | /// Json parameters for the target method 19 | public RpcRequest(RpcId id, string method, RpcParameters parameters = default) 20 | { 21 | this.Id = id; 22 | this.Method = method; 23 | this.Parameters = parameters; 24 | } 25 | 26 | /// Target method name 27 | /// Json parameters for the target method 28 | public RpcRequest(string method, RpcParameters parameters = default) 29 | { 30 | this.Id = new RpcId(); 31 | this.Method = method; 32 | this.Parameters = parameters; 33 | } 34 | 35 | /// 36 | /// Request Id (Optional) 37 | /// 38 | public RpcId Id { get; private set; } 39 | /// 40 | /// Name of the target method (Required) 41 | /// 42 | public string Method { get; private set; } 43 | /// 44 | /// Parameters to invoke the method with (Optional) 45 | /// 46 | public RpcParameters Parameters { get; private set; } 47 | 48 | public static RpcRequest WithNoParameters(string method, RpcId id = default) 49 | { 50 | return RpcRequest.WithParameters(method, default, id); 51 | } 52 | 53 | public static RpcRequest WithParameterList(string method, IList parameterList, RpcId id = default) 54 | { 55 | parameterList = parameterList ?? new object[0]; 56 | RpcParameters parameters = RpcParameters.FromList(parameterList); 57 | return RpcRequest.WithParameters(method, parameters, id); 58 | } 59 | 60 | public static RpcRequest WithParameterMap(string method, IDictionary parameterDictionary, RpcId id = default) 61 | { 62 | parameterDictionary = parameterDictionary ?? new Dictionary(); 63 | RpcParameters parameters = RpcParameters.FromDictionary(parameterDictionary); 64 | return RpcRequest.WithParameters(method, parameters, id); 65 | } 66 | 67 | public static RpcRequest WithParameters(string method, RpcParameters parameters, RpcId id = default) 68 | { 69 | if (method == null) 70 | { 71 | throw new ArgumentNullException(nameof(method)); 72 | } 73 | return new RpcRequest(id, method, parameters); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/SerializerTests.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Router.Defaults; 3 | using Microsoft.Extensions.Options; 4 | using EdjCase.JsonRpc.Router.Abstractions; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Text; 9 | using Xunit; 10 | using System.Threading.Tasks; 11 | 12 | namespace EdjCase.JsonRpc.Router.Tests 13 | { 14 | public class SerializerTests 15 | { 16 | [Fact] 17 | public async Task ValidResponseSerialization() 18 | { 19 | var config = new RpcServerConfiguration(); 20 | IRpcResponseSerializer serializer = new DefaultRpcResponseSerializer(Options.Create(config)); 21 | 22 | const string expectedResponseString = "{\"id\":1,\"jsonrpc\":\"2.0\",\"result\":\"result\"}"; 23 | var response = new RpcResponse(1, "result"); 24 | string responseString = await serializer.SerializeAsync(response); 25 | 26 | Assert.Equal(expectedResponseString, responseString, ignoreCase: false, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); 27 | } 28 | 29 | 30 | [Fact] 31 | public async Task ValidErrorResponseSerialization() 32 | { 33 | var config = new RpcServerConfiguration(); 34 | IRpcResponseSerializer serializer = new DefaultRpcResponseSerializer(Options.Create(config)); 35 | 36 | const string expectedResponseString = "{\"id\":2,\"jsonrpc\":\"2.0\",\"error\":{\"code\":2,\"message\":\"error\",\"data\":\"data\"}}"; 37 | var response = new RpcResponse(2, new RpcError(2, "error", "data")); 38 | string responseString = await serializer.SerializeAsync(response); 39 | 40 | Assert.Equal(expectedResponseString, responseString, ignoreCase: false, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); 41 | } 42 | 43 | 44 | [Fact] 45 | public async Task ValidBulkResponseSerialization() 46 | { 47 | var config = new RpcServerConfiguration(); 48 | IRpcResponseSerializer serializer = new DefaultRpcResponseSerializer(Options.Create(config)); 49 | 50 | const string expectedResponseString = "[{\"id\":1,\"jsonrpc\":\"2.0\",\"result\":\"result\"},{\"id\":2,\"jsonrpc\":\"2.0\",\"error\":{\"code\":2,\"message\":\"error\",\"data\":\"data\"}},{\"id\":3,\"jsonrpc\":\"2.0\",\"result\":\"result3\"}]"; 51 | var response = new RpcResponse(1, "result"); 52 | var errorResponse = new RpcResponse(2, new RpcError(2, "error", "data")); 53 | var response2 = new RpcResponse(3, "result3"); 54 | string responseString = await serializer.SerializeBulkAsync(new[] { response, errorResponse, response2 }); 55 | 56 | Assert.Equal(expectedResponseString, responseString, ignoreCase: false, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Client.Tests/HttpTransportClientTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Xunit; 3 | using EdjCase.JsonRpc.Client; 4 | using Moq; 5 | using System.Net.Http; 6 | using System.Collections.Generic; 7 | using System.Threading.Tasks; 8 | using System.Net; 9 | using System.Linq; 10 | using Microsoft.Extensions.Options; 11 | using EdjCase.JsonRpc.Common.Tools; 12 | 13 | namespace EdjCase.JsonRpc.Client.Tests 14 | { 15 | public class HttpTransportClientTests 16 | { 17 | [Fact] 18 | public async Task InvalidExceptionWithBadStatusCode() 19 | { 20 | var uri = new Uri("https://test.com/test"); 21 | foreach (HttpStatusCode statusCode in Enum.GetValues(typeof(HttpStatusCode)).Cast()) 22 | { 23 | var responseMessage = new HttpResponseMessage(statusCode); 24 | responseMessage.Content = new StringContent("Bad"); 25 | var fakeHandler = new FakeResponseHandler(); 26 | fakeHandler.AddFakeResponse(uri, responseMessage); 27 | var factory = new Mock(MockBehavior.Strict); 28 | factory 29 | .Setup(f => f.CreateClient(Options.DefaultName)) 30 | .Returns(new HttpClient(fakeHandler)); 31 | var streamCompressor = new Mock(MockBehavior.Strict); 32 | System.IO.Stream stream; 33 | streamCompressor 34 | .Setup(c => c.TryGetCompressionStream(It.IsAny(), It.IsAny(), It.IsAny(), out stream)) 35 | .Returns(false); 36 | var client = new HttpRpcTransportClient(streamCompressor.Object, httpClientFactory: factory.Object); 37 | Func func = () => client.SendRequestAsync(uri, "{}"); 38 | if (!responseMessage.IsSuccessStatusCode) 39 | { 40 | await Assert.ThrowsAsync(func); 41 | } 42 | else 43 | { 44 | await func(); 45 | } 46 | } 47 | } 48 | } 49 | 50 | public class FakeResponseHandler : DelegatingHandler 51 | { 52 | private readonly Dictionary responses = new Dictionary(); 53 | 54 | public void AddFakeResponse(Uri uri, HttpResponseMessage responseMessage) 55 | { 56 | responses.Add(uri, responseMessage); 57 | } 58 | 59 | protected override Task SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) 60 | { 61 | HttpResponseMessage message; 62 | if (responses.ContainsKey(request.RequestUri)) 63 | { 64 | message = responses[request.RequestUri]; 65 | } 66 | else 67 | { 68 | message = new HttpResponseMessage(HttpStatusCode.NotFound) 69 | { 70 | RequestMessage = request 71 | }; 72 | } 73 | return Task.FromResult(message); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router.Swagger/BuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.DependencyInjection.Extensions; 6 | using Microsoft.OpenApi.Models; 7 | using Swashbuckle.AspNetCore.Swagger; 8 | using Swashbuckle.AspNetCore.SwaggerGen; 9 | using Swashbuckle.AspNetCore.SwaggerUI; 10 | 11 | namespace EdjCase.JsonRpc.Router.Swagger.Extensions 12 | { 13 | public static class StartupExtensions 14 | { 15 | public static IServiceCollection AddJsonRpcWithSwagger(this IServiceCollection services, 16 | Action? configureRpc = null, 17 | JsonSerializerOptions? jsonSerializerOptions = null, 18 | Action? configureSwaggerGen = null) 19 | { 20 | configureSwaggerGen = configureSwaggerGen ?? StartupExtensions.GetDefaultSwaggerGenOptions(); 21 | 22 | jsonSerializerOptions = jsonSerializerOptions ?? new JsonSerializerOptions(); 23 | services.TryAddSingleton(s => 24 | { 25 | return new JsonSerializerDataContractResolver(jsonSerializerOptions); 26 | }); 27 | return services 28 | //enable xml documentation generation in project options (release and debug) 29 | .AddSingleton() 30 | .AddSingleton() 31 | .AddSwaggerGen(configureSwaggerGen) 32 | .AddJsonRpc(configureRpc); 33 | } 34 | 35 | public static IApplicationBuilder UseJsonRpcWithSwagger(this IApplicationBuilder app, 36 | Action? configureRpc = null, 37 | Action? configureSwagger = null, 38 | Action? configureSwaggerUI = null) 39 | { 40 | return app 41 | .UseSwagger(configureSwagger) 42 | .UseJsonRpc(configureRpc); 43 | } 44 | public static IApplicationBuilder UseJsonRpcWithSwaggerUI(this IApplicationBuilder app, 45 | Action? configureRpc = null, 46 | Action? configureSwagger = null, 47 | Action? configureSwaggerUI = null) 48 | { 49 | return app 50 | .UseSwagger(configureSwagger) 51 | .UseSwaggerUI(configureSwaggerUI ?? StartupExtensions.GetDefaultSwaggerUIOptions()) 52 | .UseJsonRpc(configureRpc); 53 | } 54 | 55 | 56 | 57 | 58 | 59 | private static Action GetDefaultSwaggerGenOptions() 60 | { 61 | return c => c.SwaggerDoc("v1", new OpenApiInfo 62 | { 63 | Title = "My API V1", 64 | Version = "v1" 65 | }); 66 | } 67 | 68 | private static Action GetDefaultSwaggerUIOptions() 69 | { 70 | return c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/ParsingResult.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Router.Utilities; 3 | using System; 4 | using System.Buffers; 5 | using System.Collections.Generic; 6 | using System.ComponentModel; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Text.Json; 10 | 11 | namespace EdjCase.JsonRpc.Router 12 | { 13 | public class ParsingResult 14 | { 15 | /// 16 | /// Successfully parsed request 17 | /// 18 | public List Requests { get; } 19 | /// 20 | /// Errors with the associated request id 21 | /// 22 | public List<(RpcId Id, RpcError Error)> Errors { get; } 23 | /// 24 | /// Flag to indicate if the request was an array vs singular 25 | /// 26 | public bool IsBulkRequest { get; } 27 | /// 28 | /// Count of total requests processed (successful and failed) 29 | /// 30 | public int RequestCount => this.Requests.Count + this.Errors.Count; 31 | 32 | public ParsingResult(List requests, List<(RpcId, RpcError)> errors, bool isBulkRequest) 33 | { 34 | this.Requests = requests; 35 | this.Errors = errors; 36 | this.IsBulkRequest = isBulkRequest; 37 | } 38 | 39 | internal static ParsingResult FromResults(List results, bool isBulkRequest) 40 | { 41 | var requests = new List(); 42 | var errors = new List<(RpcId, RpcError)>(); 43 | foreach (RpcRequestParseResult result in results) 44 | { 45 | if (result.Error != null) 46 | { 47 | errors.Add((result.Id, result.Error)); 48 | } 49 | else 50 | { 51 | requests.Add(new RpcRequest(result.Id, result.Method!, result.Parameters)); 52 | } 53 | } 54 | //safety check 55 | isBulkRequest = isBulkRequest || (requests.Count + errors.Count > 1); 56 | return new ParsingResult(requests, errors, isBulkRequest); 57 | } 58 | } 59 | 60 | internal class RpcRequestParseResult 61 | { 62 | public RpcId Id { get; } 63 | public string? Method { get; } 64 | public TopLevelRpcParameters? Parameters { get; } 65 | public RpcError? Error { get; } 66 | private RpcRequestParseResult(RpcId id, string? method, TopLevelRpcParameters? parameters, RpcError? error) 67 | { 68 | this.Id = id; 69 | this.Method = method; 70 | this.Parameters = parameters; 71 | this.Error = error; 72 | } 73 | 74 | public static RpcRequestParseResult Success(RpcId id, string method, TopLevelRpcParameters? parameters) 75 | { 76 | return new RpcRequestParseResult(id, method, parameters, null); 77 | } 78 | 79 | public static RpcRequestParseResult Fail(RpcId id, RpcError error) 80 | { 81 | return new RpcRequestParseResult(id, null, null, error); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Defaults/DefaultAuthorizationHandler.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router.Abstractions; 2 | using EdjCase.JsonRpc.Router.Utilities; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Http; 5 | using Microsoft.Extensions.Logging; 6 | using System; 7 | using System.Collections.Concurrent; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Reflection; 11 | using System.Security.Claims; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace EdjCase.JsonRpc.Router.Defaults 16 | { 17 | internal class DefaultAuthorizationHandler : IRpcAuthorizationHandler 18 | { 19 | private ILogger logger { get; } 20 | /// 21 | /// Provides authorization policies for the authroziation service 22 | /// 23 | private IAuthorizationPolicyProvider policyProvider { get; } 24 | private IHttpContextAccessor httpContextAccessor { get; } 25 | 26 | /// 27 | /// AspNet service to authorize requests 28 | /// 29 | private IAuthorizationService authorizationService { get; } 30 | public DefaultAuthorizationHandler(ILogger logger, 31 | IAuthorizationPolicyProvider policyProvider, 32 | IAuthorizationService authorizationService, 33 | IHttpContextAccessor httpContextAccessor) 34 | { 35 | this.logger = logger; 36 | this.policyProvider = policyProvider; 37 | this.authorizationService = authorizationService; 38 | this.httpContextAccessor = httpContextAccessor; 39 | } 40 | public async Task IsAuthorizedAsync(IRpcMethodInfo methodInfo) 41 | { 42 | if (methodInfo.AuthorizeDataList.Any()) 43 | { 44 | if (methodInfo.AllowAnonymous) 45 | { 46 | this.logger.SkippingAuth(); 47 | } 48 | else 49 | { 50 | this.logger.RunningAuth(); 51 | AuthorizationResult authResult = await this.CheckAuthorize(methodInfo.AuthorizeDataList); 52 | if (authResult.Succeeded) 53 | { 54 | this.logger.AuthSuccessful(); 55 | } 56 | else 57 | { 58 | this.logger.AuthFailed(); 59 | return false; 60 | } 61 | } 62 | } 63 | else 64 | { 65 | this.logger.NoConfiguredAuth(); 66 | } 67 | return true; 68 | } 69 | 70 | private async Task CheckAuthorize(IReadOnlyList authorizeDataList) 71 | { 72 | if (!authorizeDataList.Any()) 73 | { 74 | return AuthorizationResult.Success(); 75 | } 76 | AuthorizationPolicy policy = (await AuthorizationPolicy.CombineAsync(this.policyProvider, authorizeDataList))!; 77 | ClaimsPrincipal claimsPrincipal = this.httpContextAccessor.HttpContext!.User; 78 | return await this.authorizationService.AuthorizeAsync(claimsPrincipal, policy); 79 | } 80 | 81 | 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/IRpcParameter.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router.Utilities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Text; 6 | using System.Text.Json; 7 | 8 | namespace EdjCase.JsonRpc.Router 9 | { 10 | public class RpcParameter 11 | { 12 | public RpcParameterType Type { get; } 13 | private object? value { get; } 14 | 15 | private RpcParameter(RpcParameterType type, object? value) 16 | { 17 | this.Type = type; 18 | this.value = value; 19 | } 20 | 21 | public bool GetIfNullIsSpecified() 22 | { 23 | this.ThrowIfNoType(RpcParameterType.Null); 24 | return (bool)this.value!; 25 | } 26 | public bool GetBooleanValue() 27 | { 28 | this.ThrowIfNoType(RpcParameterType.Boolean); 29 | return (bool)this.value!; 30 | } 31 | public RpcNumber GetNumberValue() 32 | { 33 | this.ThrowIfNoType(RpcParameterType.Number); 34 | return (RpcNumber)this.value!; 35 | } 36 | public string GetStringValue() 37 | { 38 | this.ThrowIfNoType(RpcParameterType.String); 39 | return (string)this.value!; 40 | } 41 | 42 | public Dictionary GetObjectValue() 43 | { 44 | this.ThrowIfNoType(RpcParameterType.Object); 45 | return (Dictionary)this.value!; 46 | } 47 | 48 | public RpcParameter[] GetArrayValue() 49 | { 50 | this.ThrowIfNoType(RpcParameterType.Array); 51 | return (RpcParameter[])this.value!; 52 | } 53 | 54 | private void ThrowIfNoType(RpcParameterType type) 55 | { 56 | if (this.Type != type) 57 | { 58 | throw new InvalidOperationException($"Cannot get a {type} value from a {this.Type} value"); 59 | } 60 | } 61 | 62 | public static RpcParameter String(string value) 63 | { 64 | return new RpcParameter(RpcParameterType.String, value); 65 | } 66 | 67 | public static RpcParameter Number(RpcNumber value) 68 | { 69 | return new RpcParameter(RpcParameterType.Number, value); 70 | } 71 | 72 | public static RpcParameter Boolean(bool value) 73 | { 74 | return new RpcParameter(RpcParameterType.Boolean, value); 75 | } 76 | 77 | public static RpcParameter Null(bool isSpecified) 78 | { 79 | return new RpcParameter(RpcParameterType.Null, isSpecified); 80 | } 81 | 82 | public static RpcParameter Object(Dictionary value) 83 | { 84 | return new RpcParameter(RpcParameterType.Object, value); 85 | } 86 | 87 | public static RpcParameter Array(RpcParameter[] value) 88 | { 89 | return new RpcParameter(RpcParameterType.Array, value); 90 | } 91 | } 92 | 93 | public enum RpcParameterType 94 | { 95 | Null, 96 | Boolean, 97 | Number, 98 | String, 99 | Object, 100 | Array 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Abstractions/IRpcRequestHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Buffers; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Runtime.CompilerServices; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using EdjCase.JsonRpc.Router.Utilities; 10 | 11 | namespace EdjCase.JsonRpc.Router.Abstractions 12 | { 13 | public interface IRpcRequestHandler 14 | { 15 | /// 16 | /// Takes in the request bytes and context, invokes the rpc request and then 17 | /// sets the response bytes if there is a response 18 | /// 19 | /// Contextual information about the request being handled 20 | /// The request byte stream 21 | /// An writable stream to write the response to 22 | /// True if there is a response. If false, no bytes will be written to the stream 23 | Task HandleRequestAsync(RpcContext context, Stream requestBody, Stream responseBody); 24 | 25 | /// 26 | /// Takes in the request bytes and context, invokes the rpc request and then returns 27 | /// the response bytes if there is a response 28 | /// 29 | /// Contextual information about the request being handled 30 | /// The request bytes 31 | /// The response bytes or null (if there is no response) 32 | public virtual async Task HandleRequestAsync(RpcContext context, byte[] requestBody) 33 | { 34 | using (var requestStream = new MemoryStream(requestBody)) 35 | { 36 | using (var responseStream = new MemoryStream()) 37 | { 38 | bool hasResponse = await this.HandleRequestAsync(context, requestStream, responseStream); 39 | if (!hasResponse) 40 | { 41 | return null; 42 | } 43 | responseStream.Position = 0; 44 | return responseStream.ToArray(); 45 | } 46 | } 47 | } 48 | 49 | /// 50 | /// Takes in the request json and context, invokes the rpc request and then returns 51 | /// the response json if there is a response 52 | /// 53 | /// Contextual information about the request being handled 54 | /// The request json 55 | /// The response json or null (if there is no response) 56 | public virtual async Task HandleRequestAsync(RpcContext context, string requestJson) 57 | { 58 | using (var requestStream = StreamUtil.GetStreamFromUtf8String(requestJson)) 59 | { 60 | using (var responseStream = new MemoryStream()) 61 | { 62 | bool hasResponse = await this.HandleRequestAsync(context, requestStream, responseStream); 63 | if (!hasResponse) 64 | { 65 | return null; 66 | } 67 | responseStream.Position = 0; 68 | using (var stream = new StreamReader(responseStream)) 69 | { 70 | return await stream.ReadToEndAsync(); 71 | } 72 | } 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router.Swagger/IXmlDocumentationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Xml.XPath; 5 | using EdjCase.JsonRpc.Router.Abstractions; 6 | using Swashbuckle.AspNetCore.SwaggerGen; 7 | 8 | namespace EdjCase.JsonRpc.Router.Swagger 9 | { 10 | public interface IXmlDocumentationService 11 | { 12 | string GetSummaryForType(Type type); 13 | string GetSummaryForMethod(IRpcMethodInfo methodInfo); 14 | string GetMethodParameterExample(IRpcMethodInfo methodInfo, IRpcParameterInfo parameterInfo); 15 | string GetPropertyExample(PropertyInfo propertyInfo); 16 | } 17 | 18 | public class XmlDocumentationService : IXmlDocumentationService 19 | { 20 | private XPathNavigator xpathNavigator; 21 | private const string MemberXPath = "/doc/members/member[@name='{0}']"; 22 | private const string SummaryTag = "summary"; 23 | 24 | public XmlDocumentationService() 25 | { 26 | var filePath = Path.Combine(System.AppContext.BaseDirectory, $"{Assembly.GetEntryAssembly()!.GetName().Name}.xml"); 27 | if (File.Exists(filePath)) 28 | { 29 | var xmlComments = File.OpenText(filePath); 30 | var xpathDocument = new XPathDocument(xmlComments); 31 | this.xpathNavigator = xpathDocument.CreateNavigator(); 32 | } 33 | else 34 | { 35 | var xpathDocument = new XPathDocument(new StringReader("")); 36 | this.xpathNavigator = xpathDocument.CreateNavigator(); 37 | } 38 | } 39 | 40 | public string GetSummaryForType(Type type) 41 | { 42 | var memberName = XmlCommentsNodeNameHelper.GetMemberNameForType(type); 43 | var typeNode = this.xpathNavigator.SelectSingleNode(string.Format(XmlDocumentationService.MemberXPath, memberName)); 44 | if (typeNode == null) return string.Empty; 45 | var summaryNode = typeNode.SelectSingleNode(XmlDocumentationService.SummaryTag); 46 | return XmlCommentsTextHelper.Humanize(summaryNode!.InnerXml); 47 | } 48 | 49 | public string GetSummaryForMethod(IRpcMethodInfo methodInfo) 50 | { 51 | var methodNode = this.xpathNavigator.SelectSingleNode($"/doc/members/member[@name='{methodInfo.Name}']"); 52 | var summaryNode = methodNode?.SelectSingleNode("summary"); 53 | return summaryNode != null ? XmlCommentsTextHelper.Humanize(summaryNode.InnerXml) : string.Empty; 54 | } 55 | 56 | public string GetMethodParameterExample(IRpcMethodInfo methodInfo, IRpcParameterInfo parameterInfo) 57 | { 58 | var paramNode = this.xpathNavigator.SelectSingleNode( 59 | $"/doc/members/member[@name='{methodInfo.Name}']/param[@name='{parameterInfo.Name}']"); 60 | if (paramNode == null) return string.Empty; 61 | var example = paramNode.GetAttribute("example", ""); 62 | return example; 63 | } 64 | 65 | public string GetPropertyExample(PropertyInfo propertyInfo) 66 | { 67 | var propertyMemberName = XmlCommentsNodeNameHelper.GetMemberNameForFieldOrProperty(propertyInfo); 68 | var propertyExampleNode = this.xpathNavigator.SelectSingleNode($"/doc/members/member[@name='{propertyMemberName}']/example"); 69 | if (propertyExampleNode == null) return string.Empty; 70 | var example = XmlCommentsTextHelper.Humanize(propertyExampleNode.InnerXml); 71 | return example; 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Utilities/JsonStringGeneratorUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | using System.Text.Json; 6 | 7 | namespace EdjCase.JsonRpc.Router.Utilities 8 | { 9 | internal class JsonStringGeneratorUtil 10 | { 11 | private delegate void WriteJson(T value, ref Utf8JsonWriter writer); 12 | 13 | public static string FromObject(Dictionary obj, JsonSerializerOptions? options = null) 14 | { 15 | return JsonStringGeneratorUtil.From(obj, JsonStringGeneratorUtil.WriteObject, options); 16 | } 17 | 18 | public static string FromArray(RpcParameter[] array, JsonSerializerOptions? options = null) 19 | { 20 | return JsonStringGeneratorUtil.From(array, JsonStringGeneratorUtil.WriteArray, options); 21 | } 22 | 23 | private static string From(T value, WriteJson writeJsonFunc, JsonSerializerOptions? options) 24 | { 25 | using (var utf8Stream = new MemoryStream()) 26 | { 27 | JsonWriterOptions writerOptions = options.ToWriterOptions(); 28 | var writer = new Utf8JsonWriter(utf8Stream, writerOptions); 29 | try 30 | { 31 | writeJsonFunc(value, ref writer); 32 | 33 | writer.Flush(); 34 | 35 | //Convert to string 36 | return Encoding.UTF8.GetString(utf8Stream.ToArray()); 37 | } 38 | finally 39 | { 40 | writer.Dispose(); 41 | } 42 | } 43 | } 44 | 45 | 46 | private static void WriteObject(Dictionary obj, ref Utf8JsonWriter writer) 47 | { 48 | writer.WriteStartObject(); 49 | foreach ((string propertyName, RpcParameter value) in obj) 50 | { 51 | writer.WritePropertyName(propertyName); 52 | JsonStringGeneratorUtil.WriteValue(value, ref writer); 53 | } 54 | writer.WriteEndObject(); 55 | } 56 | 57 | private static void WriteArray(RpcParameter[] values, ref Utf8JsonWriter writer) 58 | { 59 | writer.WriteStartArray(); 60 | foreach (RpcParameter value in values) 61 | { 62 | JsonStringGeneratorUtil.WriteValue(value, ref writer); 63 | } 64 | writer.WriteEndArray(); 65 | } 66 | 67 | private static void WriteValue(RpcParameter value, ref Utf8JsonWriter writer) 68 | { 69 | switch (value.Type) 70 | { 71 | case RpcParameterType.Array: 72 | JsonStringGeneratorUtil.WriteArray(value.GetArrayValue(), ref writer); 73 | break; 74 | case RpcParameterType.Null: 75 | writer.WriteNullValue(); 76 | break; 77 | case RpcParameterType.Boolean: 78 | writer.WriteBooleanValue(value.GetBooleanValue()); 79 | break; 80 | case RpcParameterType.Number: 81 | RpcNumber number = value.GetNumberValue(); 82 | if(!number.TryGetDecimal(out decimal v)) 83 | { 84 | throw new NotImplementedException($"Could not parse {number} as a decimal"); 85 | } 86 | writer.WriteNumberValue(v); 87 | break; 88 | case RpcParameterType.String: 89 | writer.WriteStringValue(value.GetStringValue()); 90 | break; 91 | case RpcParameterType.Object: 92 | JsonStringGeneratorUtil.WriteObject(value.GetObjectValue(), ref writer); 93 | break; 94 | default: 95 | throw new NotImplementedException(); 96 | } 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcEndpointBuilder.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using EdjCase.JsonRpc.Router.Abstractions; 7 | 8 | namespace EdjCase.JsonRpc.Router 9 | { 10 | public class RpcEndpointBuilder 11 | { 12 | private List baseMethods { get; } = new List(); 13 | private Dictionary> methods { get; } = new Dictionary>(); 14 | 15 | public RpcEndpointBuilder AddMethod(MethodInfo methodInfo, RpcPath? path = null) 16 | { 17 | IRpcMethodInfo rpcMethodInfo = DefaultRpcMethodInfo.FromMethodInfo(methodInfo); 18 | this.Add(path, rpcMethodInfo); 19 | return this; 20 | } 21 | public RpcEndpointBuilder AddMethod(IRpcMethodInfo methodInfo, RpcPath? path = null) 22 | { 23 | this.Add(path, methodInfo); 24 | return this; 25 | } 26 | 27 | public RpcEndpointBuilder AddController() 28 | { 29 | Type controllerType = typeof(T); 30 | return this.AddController(controllerType); 31 | } 32 | public RpcEndpointBuilder AddController(Type controllerType) 33 | { 34 | var attribute = controllerType.GetCustomAttribute(true); 35 | ReadOnlySpan routePathString; 36 | if (attribute == null || attribute.RouteName == null) 37 | { 38 | if (controllerType.Name.EndsWith("Controller")) 39 | { 40 | routePathString = controllerType.Name.AsSpan(0, controllerType.Name.IndexOf("Controller")); 41 | } 42 | else 43 | { 44 | routePathString = controllerType.Name.AsSpan(); 45 | } 46 | } 47 | else 48 | { 49 | routePathString = attribute.RouteName.AsSpan(); 50 | } 51 | RpcPath routePath = RpcPath.Parse(routePathString); 52 | return this.AddControllerWithCustomPath(controllerType, routePath); 53 | } 54 | 55 | public RpcEndpointBuilder AddControllerWithCustomPath(RpcPath? path = null) 56 | { 57 | Type controllerType = typeof(T); 58 | return this.AddControllerWithCustomPath(controllerType, path); 59 | } 60 | public RpcEndpointBuilder AddControllerWithCustomPath(Type type, RpcPath? path = null) 61 | { 62 | IEnumerable methods = RpcEndpointBuilder.Extract(type); 63 | foreach (MethodInfo methodInfo in methods) 64 | { 65 | this.AddMethod(methodInfo, path); 66 | } 67 | return this; 68 | } 69 | 70 | internal RpcRouteMetaData Resolve() 71 | { 72 | IReadOnlyDictionary> pathMethods = this.methods 73 | .ToDictionary(kv => kv.Key, kv => (IReadOnlyList)kv.Value); 74 | return new RpcRouteMetaData(this.baseMethods, pathMethods); 75 | } 76 | 77 | private static IEnumerable Extract(Type controllerType) 78 | { 79 | return controllerType.Assembly.GetTypes() 80 | .Where(t => t == controllerType) 81 | .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance)) 82 | .Where(m => m.DeclaringType != typeof(object) && m.DeclaringType != typeof(RpcController)) 83 | // Skip NonRpcMethod decorated method 84 | .Where(m => m.GetCustomAttribute(true) == null); 85 | } 86 | 87 | private void Add(RpcPath? path, IRpcMethodInfo methodInfo) 88 | { 89 | List methods; 90 | if (path == null) 91 | { 92 | methods = this.baseMethods; 93 | } 94 | else 95 | { 96 | if (!this.methods.TryGetValue(path, out List? m)) 97 | { 98 | methods = this.methods[path] = new List(); 99 | } 100 | else 101 | { 102 | methods = m!; 103 | } 104 | } 105 | methods.Add(methodInfo); 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Common/RpcId.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common.Utilities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace EdjCase.JsonRpc.Common 7 | { 8 | public enum RpcIdType 9 | { 10 | String, 11 | Number 12 | } 13 | 14 | public struct RpcId : IEquatable 15 | { 16 | public bool HasValue { get; } 17 | 18 | public RpcIdType Type { get; } 19 | 20 | public object? Value { get; } 21 | 22 | public long NumberValue 23 | { 24 | get 25 | { 26 | if (this.Type != RpcIdType.Number) 27 | { 28 | throw new InvalidOperationException("Cannot cast id to number."); 29 | } 30 | return (long)this.Value!; 31 | } 32 | } 33 | 34 | public string StringValue 35 | { 36 | get 37 | { 38 | if (this.Type != RpcIdType.String) 39 | { 40 | throw new InvalidOperationException("Cannot cast id to string."); 41 | } 42 | return (string)this.Value!; 43 | } 44 | } 45 | 46 | public RpcId(string id) 47 | { 48 | this.HasValue = true; 49 | this.Value = id; 50 | this.Type = RpcIdType.String; 51 | } 52 | 53 | public RpcId(long id) 54 | { 55 | this.HasValue = true; 56 | this.Value = id; 57 | this.Type = RpcIdType.Number; 58 | } 59 | 60 | public static bool operator ==(RpcId x, RpcId y) 61 | { 62 | return x.Equals(y); 63 | } 64 | 65 | public static bool operator !=(RpcId x, RpcId y) 66 | { 67 | return !x.Equals(y); 68 | } 69 | 70 | public bool Equals(RpcId other) 71 | { 72 | if (this.HasValue && other.HasValue) 73 | { 74 | return true; 75 | } 76 | if (this.HasValue || other.HasValue) 77 | { 78 | return false; 79 | } 80 | if (this.Type != other.Type) 81 | { 82 | return false; 83 | } 84 | return this.Type switch 85 | { 86 | RpcIdType.Number => this.NumberValue == other.NumberValue, 87 | RpcIdType.String => this.StringValue == other.StringValue, 88 | _ => throw new ArgumentOutOfRangeException(nameof(this.Type)), 89 | }; 90 | } 91 | 92 | public override bool Equals(object? obj) 93 | { 94 | if (obj is RpcId id) 95 | { 96 | return this.Equals(id); 97 | } 98 | return false; 99 | } 100 | 101 | public override int GetHashCode() 102 | { 103 | if (!this.HasValue) 104 | { 105 | return 0; 106 | } 107 | return this.Value!.GetHashCode(); 108 | } 109 | 110 | public override string? ToString() 111 | { 112 | if (!this.HasValue) 113 | { 114 | return string.Empty; 115 | } 116 | return this.Type switch 117 | { 118 | RpcIdType.Number => this.Value!.ToString(), 119 | RpcIdType.String => "'" + (string)this.Value! + "'", 120 | _ => throw new ArgumentOutOfRangeException(nameof(this.Type)), 121 | }; 122 | } 123 | 124 | public static implicit operator RpcId(long id) 125 | { 126 | return new RpcId(id); 127 | } 128 | 129 | public static RpcId FromInt64(long id) 130 | { 131 | return new RpcId(id); 132 | } 133 | 134 | public static implicit operator RpcId(string id) 135 | { 136 | return new RpcId(id); 137 | } 138 | 139 | public static RpcId FromString(string id) 140 | { 141 | return new RpcId(id); 142 | } 143 | 144 | public static RpcId FromObject(object value) 145 | { 146 | if (value == null) 147 | { 148 | return default; 149 | } 150 | if (value is RpcId rpcId) 151 | { 152 | return rpcId; 153 | } 154 | if (value is string stringValue) 155 | { 156 | return new RpcId(stringValue); 157 | } 158 | if (value.GetType().IsNumericType()) 159 | { 160 | return new RpcId(Convert.ToInt64(value)); 161 | } 162 | throw new RpcException(RpcErrorCode.InvalidRequest, "Id must be a string, a number or null."); 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studo 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | *_i.c 42 | *_p.c 43 | *_i.h 44 | *.ilk 45 | *.meta 46 | *.obj 47 | *.pch 48 | *.pdb 49 | *.pgc 50 | *.pgd 51 | *.rsp 52 | *.sbr 53 | *.tlb 54 | *.tli 55 | *.tlh 56 | *.tmp 57 | *.tmp_proj 58 | *.log 59 | *.vspscc 60 | *.vssscc 61 | .builds 62 | *.pidb 63 | *.svclog 64 | *.scc 65 | 66 | # Chutzpah Test files 67 | _Chutzpah* 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | *.cachefile 76 | 77 | # Visual Studio profiler 78 | *.psess 79 | *.vsp 80 | *.vspx 81 | 82 | # TFS 2012 Local Workspace 83 | $tf/ 84 | 85 | # Guidance Automation Toolkit 86 | *.gpState 87 | 88 | # ReSharper is a .NET coding add-in 89 | _ReSharper*/ 90 | *.[Rr]e[Ss]harper 91 | *.DotSettings.user 92 | 93 | # JustCode is a .NET coding addin-in 94 | .JustCode 95 | 96 | # TeamCity is a build add-in 97 | _TeamCity* 98 | 99 | # DotCover is a Code Coverage Tool 100 | *.dotCover 101 | 102 | # NCrunch 103 | _NCrunch_* 104 | .*crunch*.local.xml 105 | 106 | # MightyMoose 107 | *.mm.* 108 | AutoTest.Net/ 109 | 110 | # Web workbench (sass) 111 | .sass-cache/ 112 | 113 | # Installshield output folder 114 | [Ee]xpress/ 115 | 116 | # DocProject is a documentation generator add-in 117 | DocProject/buildhelp/ 118 | DocProject/Help/*.HxT 119 | DocProject/Help/*.HxC 120 | DocProject/Help/*.hhc 121 | DocProject/Help/*.hhk 122 | DocProject/Help/*.hhp 123 | DocProject/Help/Html2 124 | DocProject/Help/html 125 | 126 | # Click-Once directory 127 | publish/ 128 | 129 | # Publish Web Output 130 | *.[Pp]ublish.xml 131 | *.azurePubxml 132 | # TODO: Comment the next line if you want to checkin your web deploy settings 133 | # but database connection strings (with potential passwords) will be unencrypted 134 | *.pubxml 135 | *.publishproj 136 | 137 | # NuGet Packages 138 | *.nupkg 139 | # The packages folder can be ignored because of Package Restore 140 | **/packages/* 141 | # except build/, which is used as an MSBuild target. 142 | !**/packages/build/ 143 | # Uncomment if necessary however generally it will be regenerated when needed 144 | #!**/packages/repositories.config 145 | 146 | # Windows Azure Build Output 147 | csx/ 148 | *.build.csdef 149 | 150 | # Windows Store app package directory 151 | AppPackages/ 152 | 153 | # Others 154 | *.[Cc]ache 155 | ClientBin/ 156 | [Ss]tyle[Cc]op.* 157 | ~$* 158 | *~ 159 | *.dbmdl 160 | *.dbproj.schemaview 161 | *.pfx 162 | *.publishsettings 163 | node_modules/ 164 | bower_components/ 165 | 166 | # RIA/Silverlight projects 167 | Generated_Code/ 168 | 169 | # Backup & report files from converting an old project file 170 | # to a newer Visual Studio version. Backup files are not needed, 171 | # because we have git ;-) 172 | _UpgradeReport_Files/ 173 | Backup*/ 174 | UpgradeLog*.XML 175 | UpgradeLog*.htm 176 | 177 | # SQL Server files 178 | *.mdf 179 | *.ldf 180 | 181 | # Business Intelligence projects 182 | *.rdl.data 183 | *.bim.layout 184 | *.bim_*.settings 185 | 186 | # Microsoft Fakes 187 | FakesAssemblies/ 188 | 189 | # Node.js Tools for Visual Studio 190 | .ntvs_analysis.dat 191 | 192 | # Visual Studio 6 build log 193 | *.plg 194 | 195 | # Visual Studio 6 workspace options file 196 | *.opt 197 | project.lock.json 198 | 199 | # Rider workspace options directory 200 | .idea 201 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Defaults/DefaultRpcResponseSerializer.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Router.Abstractions; 3 | using EdjCase.JsonRpc.Router.Utilities; 4 | using Microsoft.Extensions.Options; 5 | using System; 6 | using System.Buffers.Text; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Text; 11 | using System.Text.Json; 12 | using System.Threading.Tasks; 13 | 14 | namespace EdjCase.JsonRpc.Router.Defaults 15 | { 16 | internal class DefaultRpcResponseSerializer : IRpcResponseSerializer 17 | { 18 | private IOptions serverConfig { get; } 19 | public DefaultRpcResponseSerializer(IOptions serverConfig) 20 | { 21 | this.serverConfig = serverConfig; 22 | } 23 | 24 | public Task SerializeBulkAsync(IEnumerable responses, Stream stream) 25 | { 26 | return this.SerializeInternalAsync(responses, isBulkRequest: true, stream); 27 | } 28 | 29 | public Task SerializeAsync(RpcResponse response, Stream stream) 30 | { 31 | return this.SerializeInternalAsync(new[] { response }, isBulkRequest: false, stream); 32 | } 33 | 34 | private async Task SerializeInternalAsync(IEnumerable responses, bool isBulkRequest, Stream stream) 35 | { 36 | JsonWriterOptions options = this.serverConfig.Value.JsonSerializerSettings.ToWriterOptions(); 37 | var jsonWriter = new Utf8JsonWriter(stream, options); 38 | try 39 | { 40 | if (isBulkRequest) 41 | { 42 | jsonWriter.WriteStartArray(); 43 | foreach (RpcResponse response in responses) 44 | { 45 | this.SerializeResponse(response, jsonWriter); 46 | } 47 | jsonWriter.WriteEndArray(); 48 | } 49 | else 50 | { 51 | this.SerializeResponse(responses.Single(), jsonWriter); 52 | } 53 | } 54 | finally 55 | { 56 | await jsonWriter.FlushAsync(); 57 | await jsonWriter.DisposeAsync(); 58 | } 59 | } 60 | 61 | private void SerializeResponse(RpcResponse response, Utf8JsonWriter jsonWriter) 62 | { 63 | jsonWriter.WriteStartObject(); 64 | jsonWriter.WritePropertyName(JsonRpcContants.IdPropertyName); 65 | switch (response.Id.Type) 66 | { 67 | case RpcIdType.Number: 68 | jsonWriter.WriteNumberValue(response.Id.NumberValue); 69 | break; 70 | case RpcIdType.String: 71 | jsonWriter.WriteStringValue(response.Id.StringValue); 72 | break; 73 | default: 74 | throw new NotImplementedException(); 75 | } 76 | jsonWriter.WriteString(JsonRpcContants.VersionPropertyName, "2.0"); 77 | if (!response.HasError) 78 | { 79 | jsonWriter.WritePropertyName(JsonRpcContants.ResultPropertyName); 80 | 81 | this.SerializeValue(response.Result!, jsonWriter); 82 | } 83 | else 84 | { 85 | jsonWriter.WritePropertyName(JsonRpcContants.ErrorPropertyName); 86 | jsonWriter.WriteStartObject(); 87 | jsonWriter.WriteNumber(JsonRpcContants.ErrorCodePropertyName, response.Error!.Code); 88 | jsonWriter.WriteString(JsonRpcContants.ErrorMessagePropertyName, response.Error.Message); 89 | jsonWriter.WritePropertyName(JsonRpcContants.ErrorDataPropertyName); 90 | this.SerializeValue(response.Error.Data, jsonWriter); 91 | jsonWriter.WriteEndObject(); 92 | } 93 | jsonWriter.WriteEndObject(); 94 | } 95 | 96 | private void SerializeValue(object? value, Utf8JsonWriter jsonWriter) 97 | { 98 | if (value != null) 99 | { 100 | JsonSerializerOptions? options = this.serverConfig.Value.JsonSerializerSettings; 101 | 102 | //TODO a better way? cant figure out how to serialize an object to the writer in an async way 103 | //JsonSerializer.Serialize(jsonWriter, value, value.GetType(), options) does not work because kestrel doesnt allow non-async calls 104 | byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(value, value.GetType(), options); 105 | JsonDocument.Parse(jsonBytes).WriteTo(jsonWriter); 106 | } 107 | else 108 | { 109 | jsonWriter.WriteNullValue(); 110 | } 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcMethodInfo.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router; 2 | using EdjCase.JsonRpc.Common.Utilities; 3 | using EdjCase.JsonRpc.Router.Utilities; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Reflection; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using EdjCase.JsonRpc.Router.Abstractions; 11 | using Microsoft.AspNetCore.Authorization; 12 | using Microsoft.Extensions.DependencyInjection; 13 | 14 | namespace EdjCase.JsonRpc.Router 15 | { 16 | internal class DefaultRpcMethodInfo : IRpcMethodInfo 17 | { 18 | private readonly MethodInfo methodInfo; 19 | private readonly ObjectFactory objectFactory; 20 | public string Name => this.methodInfo.Name; 21 | 22 | public IReadOnlyList Parameters { get; } 23 | 24 | public bool AllowAnonymous { get; } 25 | 26 | public IReadOnlyList AuthorizeDataList { get; } 27 | 28 | public Type RawReturnType => this.methodInfo.ReturnType; 29 | 30 | private DefaultRpcMethodInfo( 31 | MethodInfo methodInfo, 32 | IReadOnlyList parameters, 33 | ObjectFactory objectFactory, 34 | bool allowAnonymous, 35 | IReadOnlyList authorizeDataList) 36 | { 37 | this.methodInfo = methodInfo; 38 | this.Parameters = parameters; 39 | this.objectFactory = objectFactory; 40 | this.AllowAnonymous = allowAnonymous; 41 | this.AuthorizeDataList = authorizeDataList; 42 | } 43 | 44 | public static DefaultRpcMethodInfo FromMethodInfo(MethodInfo methodInfo) 45 | { 46 | RpcParameterInfo[] parameters = methodInfo.GetParameters() 47 | .Select(RpcParameterInfo.FromParameter) 48 | .ToArray(); 49 | (List authorizeDataList, bool allowAnonymous) = GetAttributeInfo(methodInfo.GetCustomAttributes()); 50 | if (methodInfo.DeclaringType != null) 51 | { 52 | (List typeAuthorizeDataList, bool typeAllowAnonymous) = GetAttributeInfo(methodInfo.DeclaringType.GetCustomAttributes()); 53 | allowAnonymous = allowAnonymous || typeAllowAnonymous; 54 | authorizeDataList.AddRange(typeAuthorizeDataList); 55 | } 56 | ObjectFactory objectFactory = ActivatorUtilities.CreateFactory(methodInfo.DeclaringType!, Array.Empty()); 57 | return new DefaultRpcMethodInfo(methodInfo, parameters, objectFactory, allowAnonymous, authorizeDataList); 58 | } 59 | 60 | private static (List Data, bool allowAnonymous) GetAttributeInfo(IEnumerable attributes) 61 | { 62 | bool allowAnonymous = false; 63 | var dataList = new List(10); 64 | foreach (Attribute attribute in attributes) 65 | { 66 | if (attribute is IAuthorizeData data) 67 | { 68 | dataList.Add(data); 69 | } 70 | if (!allowAnonymous && attribute is IAllowAnonymous) 71 | { 72 | allowAnonymous = true; 73 | } 74 | } 75 | return (dataList, allowAnonymous); 76 | } 77 | 78 | public object? Invoke(object[] parameters, IServiceProvider serviceProvider) 79 | { 80 | //Use service provider to create instance 81 | object? obj = this.objectFactory(serviceProvider, null); 82 | if (obj == null) 83 | { 84 | //Use reflection to create instance if service provider failed or is null 85 | obj = Activator.CreateInstance(this.methodInfo.DeclaringType!); 86 | } 87 | return this.methodInfo.Invoke(obj, parameters); 88 | } 89 | } 90 | 91 | internal class RpcParameterInfo : IRpcParameterInfo 92 | { 93 | public string Name { get; } 94 | public Type RawType { get; } 95 | public bool IsOptional { get; } 96 | 97 | public RpcParameterInfo(string name, Type rawType, bool isOptional) 98 | { 99 | this.Name = name; 100 | this.RawType = rawType; 101 | this.IsOptional = isOptional; 102 | } 103 | 104 | public static RpcParameterInfo FromParameter(ParameterInfo parameterInfo) 105 | { 106 | Type parameterType = parameterInfo.ParameterType; 107 | return new RpcParameterInfo(parameterInfo.Name!, parameterInfo.ParameterType, parameterInfo.IsOptional); 108 | } 109 | 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Json; 3 | using EdjCase.JsonRpc.Router.Abstractions; 4 | 5 | namespace EdjCase.JsonRpc.Router 6 | { 7 | /// 8 | /// Configuration data for the Rpc server that is shared between all middlewares 9 | /// 10 | public class RpcServerConfiguration 11 | { 12 | /// 13 | /// Json serialization settings that will be used in serialization and deserialization 14 | /// for rpc requests 15 | /// 16 | public JsonSerializerOptions? JsonSerializerSettings { get; set; } 17 | 18 | 19 | /// 20 | /// If true will show exception messages that the server rpc methods throw. Defaults to false 21 | /// 22 | public bool ShowServerExceptions { get; set; } 23 | 24 | /// 25 | /// If specified the router will throw an error if there is a batch request count 26 | /// greater than the limit 27 | /// 28 | public int? BatchRequestLimit { get; set; } 29 | 30 | /// 31 | /// If specified the router will call the specified method if the invoker throws an exception. 32 | /// The returned result object will allow handling the error 33 | /// 34 | public Func? OnInvokeException { get; set; } 35 | 36 | /// 37 | /// If specified the router will call the specified method when the invoker is called. 38 | /// 39 | public Action? OnInvokeStart { get; set; } 40 | 41 | /// 42 | /// If specified the router will call the specified method when the invoker has finished. 43 | /// 44 | public Action? OnInvokeEnd { get; set; } 45 | 46 | /// 47 | /// If true will support use Gzip and Deflate compression 48 | /// 49 | public bool UseCompression { get; set; } = true; 50 | } 51 | 52 | public class ExceptionContext 53 | { 54 | public RpcRequest Request { get; } 55 | public IServiceProvider ServiceProvider { get; } 56 | public Exception Exception { get; } 57 | public ExceptionContext(RpcRequest request, IServiceProvider serviceProvider, Exception exception) 58 | { 59 | this.Request = request; 60 | this.ServiceProvider = serviceProvider; 61 | this.Exception = exception; 62 | } 63 | } 64 | 65 | public class OnExceptionResult 66 | { 67 | public bool ThrowException { get; } 68 | public object? ResponseObject { get; } 69 | 70 | private OnExceptionResult(bool throwException, object? responseObject) 71 | { 72 | this.ThrowException = throwException; 73 | this.ResponseObject = responseObject; 74 | } 75 | 76 | public static OnExceptionResult UseObjectResponse(object responseObject) 77 | { 78 | return new OnExceptionResult(false, responseObject); 79 | } 80 | 81 | public static OnExceptionResult UseMethodResultResponse(IRpcMethodResult result) 82 | { 83 | return new OnExceptionResult(false, result); 84 | } 85 | 86 | public static OnExceptionResult UseExceptionResponse(Exception ex) 87 | { 88 | return new OnExceptionResult(true, ex); 89 | } 90 | 91 | public static OnExceptionResult DontHandle() 92 | { 93 | return new OnExceptionResult(true, null); 94 | } 95 | } 96 | 97 | 98 | 99 | public class RpcInvokeContext 100 | { 101 | 102 | /// 103 | /// Dependency injection service provider for the request. 104 | /// 105 | public IServiceProvider ServiceProvider { get; } 106 | 107 | /// 108 | /// Current request object. 109 | /// 110 | public RpcRequest Request { get; } 111 | 112 | /// 113 | /// Current request path 114 | /// 115 | public RpcPath? Path { get; } 116 | 117 | /// 118 | /// Settable contextual data for cross-event data, such as timers for start->end of a request 119 | /// 120 | public object? CustomContextData { get; set; } 121 | 122 | internal RpcInvokeContext(IServiceProvider serviceProvider, RpcRequest request, RpcPath? path) 123 | { 124 | this.ServiceProvider = serviceProvider; 125 | this.Request = request; 126 | this.Path = path; 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/HttpClientBuilder.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Common.Tools; 3 | using Newtonsoft.Json; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Net.Http.Headers; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace EdjCase.JsonRpc.Client 11 | { 12 | public class HttpRpcClientBuilder 13 | { 14 | private IHttpAuthHeaderFactory? httpAuthHeaderFactory { get; set; } 15 | private HttpOptions options { get; } = new HttpOptions(); 16 | 17 | private Uri BaseUrl { get; } 18 | private RpcEvents Events { get; } = new RpcEvents(); 19 | private JsonSerializerSettings jsonSerializerSettings { get; } = new JsonSerializerSettings(); 20 | private Dictionary errorTypes { get; } = new Dictionary(); 21 | 22 | 23 | 24 | public HttpRpcClientBuilder(Uri baseUrl) 25 | { 26 | this.BaseUrl = baseUrl; 27 | } 28 | 29 | public HttpRpcClientBuilder ConfigureHttp(Action configure) 30 | { 31 | configure(this.options); 32 | return this; 33 | } 34 | public HttpRpcClientBuilder UsingAuthHeader(AuthenticationHeaderValue authHeader) 35 | { 36 | if (authHeader == null) 37 | { 38 | throw new ArgumentNullException(nameof(authHeader)); 39 | } 40 | if (this.httpAuthHeaderFactory != null) 41 | { 42 | throw new InvalidOperationException("Auth header factory has already been configured."); 43 | } 44 | this.httpAuthHeaderFactory = new DefaultHttpAuthHeaderFactory(authHeader); 45 | return this; 46 | } 47 | 48 | public HttpRpcClientBuilder UsingAuthHeaderFactory(IHttpAuthHeaderFactory factory) 49 | { 50 | if (factory == null) 51 | { 52 | throw new ArgumentNullException(nameof(factory)); 53 | } 54 | if (this.httpAuthHeaderFactory != null) 55 | { 56 | throw new InvalidOperationException("Auth header factory has already been configured."); 57 | } 58 | this.httpAuthHeaderFactory = factory; 59 | return this; 60 | } 61 | 62 | public HttpRpcClientBuilder UsingAuthHeaderFactory(Func> authHeaderFactory) 63 | { 64 | if (authHeaderFactory == null) 65 | { 66 | throw new ArgumentNullException(nameof(authHeaderFactory)); 67 | } 68 | if (this.httpAuthHeaderFactory != null) 69 | { 70 | throw new InvalidOperationException("Auth header factory has already been configured."); 71 | } 72 | this.httpAuthHeaderFactory = new DefaultHttpAuthHeaderFactory(authHeaderFactory); 73 | return this; 74 | } 75 | 76 | public HttpRpcClientBuilder ConfigureEvents(Action configure) 77 | { 78 | configure(this.Events); 79 | return this; 80 | } 81 | 82 | public HttpRpcClientBuilder ConfigureSerializerSettings(Action configure) 83 | { 84 | configure(this.jsonSerializerSettings); 85 | return this; 86 | } 87 | 88 | public HttpRpcClientBuilder DeserializeErrorDataAs(RpcErrorCode errorCode) 89 | { 90 | return this.DeserializeErrorDataAs((int)errorCode); 91 | } 92 | public HttpRpcClientBuilder DeserializeErrorDataAs(int errorCode) 93 | { 94 | return this.DeserializeErrorDataAs(errorCode, typeof(T)); 95 | } 96 | public HttpRpcClientBuilder DeserializeErrorDataAs(int errorCode, Type type) 97 | { 98 | this.errorTypes.Add(errorCode, type); 99 | return this; 100 | } 101 | 102 | 103 | public RpcClient Build() 104 | { 105 | var streamCompressor = new DefaultStreamCompressor(); 106 | var httpClientFactory = new DefaultHttpClientFactory(); 107 | var transportClient = new HttpRpcTransportClient( 108 | streamCompressor, 109 | httpClientFactory, 110 | encoding: this.options.Encoding, 111 | contentType: this.options.ContentType, 112 | headers: this.options.Headers, 113 | httpAuthHeaderFactory: this.httpAuthHeaderFactory); 114 | var requestSerializer = new DefaultRequestJsonSerializer(this.jsonSerializerSettings); 115 | return new RpcClient(this.BaseUrl, transportClient, requestSerializer, this.Events); 116 | } 117 | 118 | public class HttpOptions 119 | { 120 | public string ContentType { get; set; } = Defaults.ContentType; 121 | public Encoding Encoding { get; set; } = Defaults.Encoding; 122 | public List<(string, string)> Headers { get; set; } = Defaults.GetHeaders(); 123 | } 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/RpcParameterConverterTests.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router; 2 | using EdjCase.JsonRpc.Router.Defaults; 3 | using Microsoft.Extensions.Logging; 4 | using Microsoft.Extensions.Options; 5 | using Moq; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Text; 9 | using System.Text.Json; 10 | using Xunit; 11 | 12 | namespace EdjCase.JsonRpc.Router.Tests 13 | { 14 | public class RpcParameterConverterTests 15 | { 16 | private readonly Mock> options; 17 | private readonly Mock> logger; 18 | public RpcParameterConverterTests() 19 | { 20 | this.options = new Mock>(); 21 | this.logger = new Mock>(); 22 | } 23 | 24 | //TODO 25 | //[Fact] 26 | //public void TryGetValue_String_StringParsed() 27 | //{ 28 | // const string expected = "Test"; 29 | // RpcParameter param = RpcParameter.String(expected); 30 | // var converter = new DefaultRpcParameterConverter(this.options.Object, this.logger.Object); 31 | // bool parsed = converter.TryConvertValue(param, RpcParameterType.String, typeof(string), out object? actual); 32 | // Assert.True(parsed); 33 | // Assert.Equal(expected, actual); 34 | //} 35 | 36 | //[Fact] 37 | //public void TryGetValue_Number_NumberParsed() 38 | //{ 39 | // RpcParameter param = RpcParameter.Number; 40 | 41 | // bool parsed = param.TryGetValue(out int? actual); 42 | // Assert.True(parsed); 43 | // Assert.Equal(1, actual); 44 | 45 | // parsed = param.TryGetValue(out long actual2); 46 | // Assert.True(parsed); 47 | // Assert.Equal(1L, actual2); 48 | 49 | // parsed = param.TryGetValue(out short actual3); 50 | // Assert.True(parsed); 51 | // Assert.Equal(1, actual3); 52 | 53 | // parsed = param.TryGetValue(out float actual4); 54 | // Assert.True(parsed); 55 | // Assert.Equal(1f, actual4); 56 | 57 | // parsed = param.TryGetValue(out double actual5); 58 | // Assert.True(parsed); 59 | // Assert.Equal(1d, actual5); 60 | 61 | // parsed = param.TryGetValue(out decimal actual6); 62 | // Assert.True(parsed); 63 | // Assert.Equal(1m, actual6); 64 | //} 65 | 66 | //[Fact] 67 | //public void TryGetValue_DateTime_DateTimeParsed() 68 | //{ 69 | // const string expected = "2019-01-01T00:00:00.000"; 70 | // JsonBytesRpcParameter param = this.BuildParam($"\"{expected}\""); 71 | 72 | // bool parsed = param.TryGetValue(out DateTime actual); 73 | // Assert.True(parsed); 74 | // Assert.Equal(DateTime.Parse(expected), actual); 75 | 76 | // parsed = param.TryGetValue(out DateTimeOffset actual2); 77 | // Assert.True(parsed); 78 | // Assert.Equal(DateTimeOffset.Parse(expected), actual2); 79 | 80 | // parsed = param.TryGetValue(out string actual3); 81 | // Assert.True(parsed); 82 | // Assert.Equal(expected, actual3); 83 | //} 84 | 85 | //[Fact] 86 | //public void TryGetValue_Object_ObjectParsed() 87 | //{ 88 | // const string expectedDateTime = "2019-01-01T00:00:00.000"; 89 | // const decimal expectedDecimal = 1.1m; 90 | // const int expectedInteger = 1; 91 | // const string expectedString = "Test"; 92 | // string json = $"{{\"DateTime\": \"{expectedDateTime}\", \"String\": \"{expectedString}\", \"Integer\": {expectedInteger}, \"Decimal\": {expectedDecimal}}}"; 93 | 94 | // JsonBytesRpcParameter param = this.BuildParam(json); 95 | 96 | // bool parsed = param.TryGetValue(out TestObject actual); 97 | // Assert.True(parsed); 98 | // Assert.Equal(DateTime.Parse(expectedDateTime), actual.DateTime); 99 | // Assert.Equal(expectedDecimal, actual.Decimal); 100 | // Assert.Equal(expectedInteger, actual.Integer); 101 | // Assert.Equal(expectedString, actual.String); 102 | //} 103 | 104 | //private class TestObject 105 | //{ 106 | // public string? String { get; set; } 107 | // public DateTime DateTime { get; set; } 108 | // public int Integer { get; set; } 109 | // public decimal Decimal { get; set; } 110 | //} 111 | 112 | //[Fact] 113 | //public void TryGetValue_Array_ArrayParsed() 114 | //{ 115 | // string json = $"[0,1,2,3,4]"; 116 | // JsonBytesRpcParameter param = this.BuildParam(json); 117 | 118 | // bool parsed = param.TryGetValue(out List actual); 119 | // Assert.True(parsed); 120 | // for (int i = 0; i < actual.Count; i++) 121 | // { 122 | // Assert.Equal(i, actual[i]); 123 | // } 124 | //} 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Client.Sample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http.Headers; 5 | using System.Threading.Tasks; 6 | using EdjCase.JsonRpc.Client; 7 | using EdjCase.JsonRpc.Common; 8 | using Microsoft.Extensions.Options; 9 | using Newtonsoft.Json.Linq; 10 | 11 | namespace EdjCase.JsonRpc.Client.Sample 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | try 18 | { 19 | IntegrationTestRunner.RunAsync().Wait(); 20 | } 21 | catch (AggregateException aEx) 22 | { 23 | foreach (Exception exception in aEx.InnerExceptions) 24 | { 25 | Console.WriteLine(exception.Message); 26 | } 27 | } 28 | catch (Exception ex) 29 | { 30 | Console.WriteLine(ex.Message); 31 | } 32 | Console.ReadLine(); 33 | } 34 | 35 | } 36 | 37 | public static class IntegrationTestRunner 38 | { 39 | private const string url = "http://localhost:62390/RpcApi/"; 40 | private static AuthenticationHeaderValue authHeaderValue { get; } = AuthenticationHeaderValue.Parse("Basic R2VrY3RlazpXZWxjMG1lIQ=="); 41 | 42 | public static async Task RunAsync() 43 | { 44 | await IntegrationTestRunner.Test1(); 45 | await IntegrationTestRunner.Test2(); 46 | //await IntegrationTestRunner.Test3(); 47 | await IntegrationTestRunner.Test4(); 48 | } 49 | 50 | private static async Task Test1() 51 | { 52 | RpcClient client = RpcClient.Builder(new Uri(url)) 53 | .UsingAuthHeader(IntegrationTestRunner.authHeaderValue) 54 | .Build(); 55 | RpcRequest request = RpcRequest.WithParameterList("CharacterCount", new[] { "Test" }, "Id1"); 56 | RpcResponse response = await client.SendAsync(request); 57 | 58 | if (response.Result.Test != 4) 59 | { 60 | throw new Exception("Test 1 failed."); 61 | } 62 | } 63 | 64 | private static async Task Test2() 65 | { 66 | RpcClient client = RpcClient.Builder(new Uri(url)) 67 | .UsingAuthHeader(IntegrationTestRunner.authHeaderValue) 68 | .Build(); 69 | var requests = new List<(RpcRequest, Type)> 70 | { 71 | (RpcRequest.WithParameterList("CharacterCount", new[] { "Test" }, "Id1"), typeof(int)), 72 | (RpcRequest.WithParameterList("CharacterCount", new[] { "Test2" }, "Id2"), typeof(int)), 73 | (RpcRequest.WithParameterList("CharacterCount", new[] { "Test23" }, "Id3"), typeof(int)) 74 | }; 75 | RpcBulkRequest bulkRequest = new RpcBulkRequest(requests); 76 | RpcBulkResponse bulkResponse = await client.SendAsync(bulkRequest); 77 | 78 | foreach (RpcResponse r in bulkResponse.GetResponses()) 79 | { 80 | switch (r.Id.StringValue) 81 | { 82 | case "Id1": 83 | if (r.Result.Test != 4) 84 | { 85 | throw new Exception("Test 2.1 failed."); 86 | } 87 | break; 88 | case "Id2": 89 | if (r.Result.Test != 5) 90 | { 91 | throw new Exception("Test 2.2 failed."); 92 | } 93 | break; 94 | case "Id3": 95 | if (r.Result.Test != 6) 96 | { 97 | throw new Exception("Test 2.3 failed."); 98 | } 99 | break; 100 | default: 101 | throw new ArgumentOutOfRangeException(nameof(r.Id)); 102 | } 103 | } 104 | } 105 | 106 | //private static async Task Test3() 107 | //{ 108 | //TODO 109 | // var additionalHeaders = new List<(string, string)> 110 | // { 111 | // ("Accept-Encoding", "gzip") 112 | // }; 113 | // RpcRequest request = RpcRequest.WithParameterList("CharacterCount", new[] { "Test" }, "Id1"); 114 | // var transportClient = new HttpRpcTransportClient(() => Task.FromResult(authHeaderValue), headers: additionalHeaders); 115 | // var compressedClient = new RpcClient(new Uri(TestRunner.url), transportClient: transportClient); 116 | // var compressedRequest = RpcRequest.WithParameterList("CharacterCount", new[] { "Test" }, "Id1"); 117 | // var compressedResponse = await compressedClient.SendRequestAsync(request, "Strings"); 118 | //} 119 | 120 | 121 | private static async Task Test4() 122 | { 123 | 124 | RpcClient client = RpcClient.Builder(new Uri(url)) 125 | .UsingAuthHeader(IntegrationTestRunner.authHeaderValue) 126 | .Build(); 127 | RpcRequest request = RpcRequest.WithParameterList("CharacterCount", new[] { "Test" }, "Id1"); 128 | RpcResponse response = await client.SendAsync(request); 129 | 130 | if (response.Result.Test != 4) 131 | { 132 | throw new Exception("Test 1 failed."); 133 | } 134 | } 135 | } 136 | 137 | 138 | public class TestObject 139 | { 140 | public int Test { get; set; } 141 | } 142 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcHttpRouter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using EdjCase.JsonRpc.Common; 8 | using EdjCase.JsonRpc.Router.Abstractions; 9 | using Microsoft.AspNetCore.Routing; 10 | using Microsoft.Extensions.Logging; 11 | using EdjCase.JsonRpc.Router.Utilities; 12 | using Microsoft.Extensions.Options; 13 | using EdjCase.JsonRpc.Router.Defaults; 14 | using Microsoft.AspNetCore.Http; 15 | using EdjCase.JsonRpc.Common.Tools; 16 | using Microsoft.Extensions.DependencyInjection; 17 | using System.Buffers; 18 | using System.Reflection; 19 | using System.IO.Compression; 20 | 21 | namespace EdjCase.JsonRpc.Router 22 | { 23 | /// 24 | /// Router for Asp.Net to direct Http Rpc requests to the correct method, invoke it and return the proper response 25 | /// 26 | internal class RpcHttpRouter : IRouter 27 | { 28 | private static readonly char[] encodingSeperators = new[] { ',', ' ' }; 29 | 30 | /// 31 | /// Generates the virtual path data for the router 32 | /// 33 | /// Virtual path context 34 | /// Virtual path data for the router 35 | public VirtualPathData? GetVirtualPath(VirtualPathContext context) 36 | { 37 | // We return null here because we're not responsible for generating the url, the route is. 38 | return null; 39 | } 40 | 41 | /// 42 | /// Takes a route/http contexts and attempts to parse, invoke, respond to an Rpc request 43 | /// 44 | /// Route context 45 | /// Task for async routing 46 | public async Task RouteAsync(RouteContext context) 47 | { 48 | ILogger? logger = context.HttpContext.RequestServices.GetService>(); 49 | try 50 | { 51 | RpcPath? requestPath; 52 | if (!context.HttpContext.Request.Path.HasValue) 53 | { 54 | requestPath = null; 55 | } 56 | else 57 | { 58 | if (!RpcPath.TryParse(context.HttpContext.Request.Path.Value.AsSpan(), out requestPath)) 59 | { 60 | logger?.LogInformation($"Could not parse the path '{context.HttpContext.Request.Path.Value}' for the " + 61 | $"request into an rpc path. Skipping rpc router middleware."); 62 | return; 63 | } 64 | } 65 | logger?.LogInformation($"Rpc request with route '{requestPath}' started."); 66 | 67 | 68 | IRpcRequestHandler requestHandler = context.HttpContext.RequestServices.GetRequiredService(); 69 | var routeContext = new RpcContext(context.HttpContext.RequestServices, requestPath); 70 | Stream writableStream = this.BuildWritableResponseStream(context.HttpContext); 71 | using (var requestBody = new MemoryStream()) 72 | { 73 | await context.HttpContext.Request.Body.CopyToAsync(requestBody); 74 | requestBody.Position = 0; 75 | bool hasResponse = await requestHandler.HandleRequestAsync(routeContext, requestBody, writableStream); 76 | if (!hasResponse) 77 | { 78 | //No response required, but status code must be 204 79 | context.HttpContext.Response.StatusCode = 204; 80 | context.MarkAsHandled(); 81 | return; 82 | } 83 | } 84 | 85 | 86 | context.MarkAsHandled(); 87 | 88 | logger?.LogInformation("Rpc request complete"); 89 | } 90 | catch (Exception ex) 91 | { 92 | string errorMessage = "Unknown exception occurred when trying to process Rpc request. Marking route unhandled"; 93 | logger?.LogException(ex, errorMessage); 94 | context.MarkAsHandled(); 95 | } 96 | } 97 | 98 | private Stream BuildWritableResponseStream(HttpContext httpContext) 99 | { 100 | httpContext.Response.ContentType = "application/json"; 101 | string? acceptEncoding = httpContext.Request.Headers["Accept-Encoding"]; 102 | if (!string.IsNullOrWhiteSpace(acceptEncoding)) 103 | { 104 | IStreamCompressor? compressor = httpContext.RequestServices.GetService(); 105 | if (compressor != null) 106 | { 107 | string[] encodings = acceptEncoding.Split(RpcHttpRouter.encodingSeperators, StringSplitOptions.RemoveEmptyEntries); 108 | foreach (string encoding in encodings) 109 | { 110 | if (compressor.TryGetCompressionStream(httpContext.Response.Body, encoding, CompressionMode.Compress, out Stream compressedStream)) 111 | { 112 | httpContext.Response.Headers.Add("Content-Encoding", encoding); 113 | return compressedStream; 114 | } 115 | } 116 | } 117 | } 118 | return httpContext.Response.Body; 119 | } 120 | } 121 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/RpcTransportClients.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using EdjCase.JsonRpc.Common.Tools; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.IO.Compression; 7 | using System.Linq; 8 | using System.Net.Http; 9 | using System.Net.Http.Headers; 10 | using System.Text; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | 14 | using System.Net.WebSockets; 15 | using Microsoft.Extensions.Options; 16 | namespace EdjCase.JsonRpc.Client 17 | { 18 | internal interface IRpcTransportClient 19 | { 20 | Task SendRequestAsync(Uri uri, Stream requestStream, CancellationToken cancellationToken = default); 21 | } 22 | 23 | internal static class RpcTransportExtensions 24 | { 25 | public static async Task SendRequestAsync(this IRpcTransportClient client, Uri uri, string requestJson, CancellationToken cancellationToken = default) 26 | { 27 | using (var requestStream = new MemoryStream(Encoding.UTF8.GetBytes(requestJson))) 28 | { 29 | using (Stream responseStream = await client.SendRequestAsync(uri, requestStream, cancellationToken)) 30 | { 31 | using (StreamReader streamReader = new StreamReader(responseStream)) 32 | { 33 | return await streamReader.ReadToEndAsync(); 34 | } 35 | } 36 | } 37 | } 38 | } 39 | 40 | internal class HttpRpcTransportClient : IRpcTransportClient 41 | { 42 | /// 43 | /// Request encoding type for json content. If null, will default to UTF-8 44 | /// 45 | public Encoding Encoding { get; } 46 | /// 47 | /// Request content type for json content. If null, will default to application/json 48 | /// 49 | public string ContentType { get; } 50 | /// 51 | /// Add headers to the underlying http client 52 | /// 53 | public IReadOnlyList<(string, string)> Headers { get; } 54 | 55 | private IStreamCompressor streamCompressor { get; } 56 | 57 | /// 58 | /// Factory to create authentication header for each request 59 | /// 60 | private IHttpAuthHeaderFactory? httpAuthHeaderFactory { get; } 61 | 62 | private IHttpClientFactory httpClientFactory { get; set; } 63 | 64 | 65 | public HttpRpcTransportClient( 66 | IStreamCompressor streamCompressor, 67 | IHttpClientFactory httpClientFactory, 68 | Encoding? encoding = null, 69 | string? contentType = null, 70 | IEnumerable<(string, string)>? headers = null, 71 | IHttpAuthHeaderFactory? httpAuthHeaderFactory = null) 72 | { 73 | this.Encoding = encoding ?? Defaults.Encoding; 74 | this.ContentType = contentType ?? Defaults.ContentType; 75 | this.Headers = headers?.ToList() ?? Defaults.GetHeaders(); 76 | this.streamCompressor = streamCompressor ?? throw new ArgumentNullException(nameof(streamCompressor)); 77 | this.httpAuthHeaderFactory = httpAuthHeaderFactory; 78 | this.httpClientFactory = httpClientFactory; 79 | } 80 | 81 | public async Task SendRequestAsync(Uri uri, Stream requestStream, CancellationToken cancellationToken = default) 82 | { 83 | HttpClient httpClient = this.httpClientFactory.CreateClient(); 84 | 85 | HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, uri); 86 | if (requestMessage.Headers.Any()) 87 | { 88 | foreach ((string key, string value) in this.Headers) 89 | { 90 | requestMessage.Headers.Add(key, value); 91 | } 92 | } 93 | if (this.httpAuthHeaderFactory != null) 94 | { 95 | requestMessage.Headers.Authorization = await this.httpAuthHeaderFactory.CreateAuthHeader(); 96 | } 97 | using (StreamReader streamReader = new StreamReader(requestStream)) 98 | { 99 | string json = await streamReader.ReadToEndAsync(); 100 | requestMessage.Content = new StringContent(json, this.Encoding, this.ContentType); 101 | } 102 | HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); 103 | 104 | Stream responseStream = await httpResponseMessage.Content.ReadAsStreamAsync(); 105 | httpResponseMessage.Content.Headers.TryGetValues("Content-Encoding", out var encodings); 106 | 107 | //handle compressions 108 | if (encodings != null && encodings.Any()) 109 | { 110 | foreach (string encoding in encodings) 111 | { 112 | if (this.streamCompressor.TryGetCompressionStream(responseStream, encoding, CompressionMode.Decompress, out Stream decompressedResponseStream)) 113 | { 114 | responseStream = decompressedResponseStream; 115 | break; 116 | } 117 | } 118 | } 119 | if (!httpResponseMessage.IsSuccessStatusCode) 120 | { 121 | using (StreamReader streamReader = new StreamReader(responseStream)) 122 | { 123 | string content = await streamReader.ReadToEndAsync(); 124 | throw new RpcClientInvalidStatusCodeException(httpResponseMessage.StatusCode, content); 125 | } 126 | } 127 | 128 | // uncompressed, standard response 129 | return responseStream; 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Tests/RequestSignatureTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Xunit; 6 | 7 | namespace EdjCase.JsonRpc.Router.Tests 8 | { 9 | public class RequestSignatureTests 10 | { 11 | [Fact] 12 | public void Create_NullListParam_Valid() 13 | { 14 | string methodName = "Test"; 15 | var signature = RpcRequestSignature.Create(methodName, parameters: (RpcParameterType[]?)null); 16 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 17 | Assert.False(signature.HasParameters); 18 | Assert.False(signature.IsDictionary); 19 | Assert.Empty(signature.ParametersAsList); 20 | } 21 | 22 | [Fact] 23 | public void Create_EmptyListParam_Valid() 24 | { 25 | string methodName = "Test"; 26 | RpcParameterType[] parameters = new RpcParameterType[0]; 27 | var signature = RpcRequestSignature.Create(methodName, parameters); 28 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 29 | Assert.False(signature.HasParameters); 30 | Assert.False(signature.IsDictionary); 31 | Assert.Equal(parameters, signature.ParametersAsList); 32 | } 33 | 34 | [Fact] 35 | public void Create_SingleListParam_Valid() 36 | { 37 | string methodName = "Test"; 38 | RpcParameterType[] parameters = new[] { RpcParameterType.String }; 39 | var signature = RpcRequestSignature.Create(methodName, parameters); 40 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 41 | Assert.True(signature.HasParameters); 42 | Assert.False(signature.IsDictionary); 43 | Assert.Equal(parameters, signature.ParametersAsList); 44 | } 45 | 46 | [Fact] 47 | public void Create_MultiListParam_Valid() 48 | { 49 | string methodName = "Test"; 50 | RpcParameterType[] parameters = new[] { RpcParameterType.String, RpcParameterType.Boolean, RpcParameterType.Null, RpcParameterType.Number, RpcParameterType.Object }; 51 | var signature = RpcRequestSignature.Create(methodName, parameters); 52 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 53 | Assert.True(signature.HasParameters); 54 | Assert.False(signature.IsDictionary); 55 | Assert.Equal(parameters, signature.ParametersAsList); 56 | } 57 | 58 | [Fact] 59 | public void Create_NullDictParam_Valid() 60 | { 61 | string methodName = "Test"; 62 | var signature = RpcRequestSignature.Create(methodName, parameters: (IEnumerable>?)null); 63 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 64 | Assert.False(signature.HasParameters); 65 | Assert.False(signature.IsDictionary); 66 | Assert.Empty(signature.ParametersAsList); 67 | } 68 | 69 | [Fact] 70 | public void Create_EmptyDictParam_Valid() 71 | { 72 | string methodName = "Test"; 73 | var parameters = new Dictionary(); 74 | var signature = RpcRequestSignature.Create(methodName, parameters); 75 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 76 | Assert.False(signature.HasParameters); 77 | Assert.True(signature.IsDictionary); 78 | this.AssertDictsEqual(parameters, signature.ParametersAsDict); 79 | } 80 | 81 | [Fact] 82 | public void Create_SingleDictParam_Valid() 83 | { 84 | string methodName = "Test"; 85 | var parameters = new Dictionary 86 | { 87 | ["Param1"] = RpcParameterType.String 88 | }; 89 | var signature = RpcRequestSignature.Create(methodName, parameters); 90 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 91 | Assert.True(signature.HasParameters); 92 | Assert.True(signature.IsDictionary); 93 | this.AssertDictsEqual(parameters, signature.ParametersAsDict); 94 | } 95 | 96 | [Fact] 97 | public void Create_MultiDictParam_Valid() 98 | { 99 | string methodName = "Test"; 100 | var parameters = new Dictionary 101 | { 102 | ["String"] = RpcParameterType.String, 103 | ["Boolean"] = RpcParameterType.Boolean, 104 | ["Null"] = RpcParameterType.Null, 105 | ["Number"] = RpcParameterType.Number, 106 | ["Object"] = RpcParameterType.Object, 107 | }; 108 | var signature = RpcRequestSignature.Create(methodName, parameters); 109 | Assert.Equal(methodName, signature.GetMethodName().ToString()); 110 | Assert.True(signature.HasParameters); 111 | Assert.True(signature.IsDictionary); 112 | this.AssertDictsEqual(parameters, signature.ParametersAsDict); 113 | } 114 | 115 | 116 | private void AssertDictsEqual(Dictionary parameters, IEnumerable<(Memory, RpcParameterType)> parametersAsDict) 117 | { 118 | int parameterCount = 0; 119 | foreach ((Memory name, RpcParameterType type) in parametersAsDict) 120 | { 121 | parameterCount++; 122 | if (!parameters.TryGetValue(name.ToString(), out RpcParameterType otherType)) 123 | { 124 | throw new Xunit.Sdk.XunitException(name.ToString()); 125 | } 126 | Assert.Equal(otherType, type); 127 | } 128 | Assert.Equal(parameters.Count, parameterCount); 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcRequestHandler.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Router; 2 | using EdjCase.JsonRpc.Common; 3 | using EdjCase.JsonRpc.Router.Abstractions; 4 | using EdjCase.JsonRpc.Router.Defaults; 5 | using EdjCase.JsonRpc.Router.Utilities; 6 | using Microsoft.Extensions.Logging; 7 | using Microsoft.Extensions.Options; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.IO; 11 | using System.Linq; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | using Microsoft.Extensions.DependencyInjection; 15 | 16 | namespace EdjCase.JsonRpc.Router 17 | { 18 | internal class RpcRequestHandler : IRpcRequestHandler 19 | { 20 | /// 21 | /// Configuration data for the server 22 | /// 23 | private IOptions serverConfig { get; } 24 | /// 25 | /// Component that invokes Rpc requests target methods and returns a response 26 | /// 27 | private IRpcInvoker invoker { get; } 28 | /// 29 | /// Component that parses Http requests into Rpc requests 30 | /// 31 | private IRpcParser parser { get; } 32 | /// 33 | /// Component that logs actions from the handler 34 | /// 35 | private ILogger logger { get; } 36 | /// 37 | /// Component that serializes all the responses to json 38 | /// 39 | private IRpcResponseSerializer responseSerializer { get; } 40 | 41 | /// Configuration data for the server 42 | /// Component that invokes Rpc requests target methods and returns a response 43 | /// Component that parses Http requests into Rpc requests 44 | /// Component that serializes all the responses to json 45 | /// Component that logs actions from the router 46 | public RpcRequestHandler(IOptions serverConfig, 47 | IRpcInvoker invoker, 48 | IRpcParser parser, 49 | IRpcResponseSerializer responseSerializer, 50 | ILogger logger) 51 | { 52 | this.serverConfig = serverConfig ?? throw new ArgumentNullException(nameof(serverConfig)); 53 | this.invoker = invoker ?? throw new ArgumentNullException(nameof(invoker)); 54 | this.parser = parser ?? throw new ArgumentNullException(nameof(parser)); 55 | this.responseSerializer = responseSerializer ?? throw new ArgumentNullException(nameof(responseSerializer)); 56 | this.logger = logger; 57 | } 58 | 59 | public async Task HandleRequestAsync(RpcContext context, Stream requestBody, Stream responseBody) 60 | { 61 | context.RequestServices.GetRequiredService().Set(context); 62 | try 63 | { 64 | ParsingResult result = this.parser.ParseRequests(requestBody); 65 | this.logger.ProcessingRequests(result.RequestCount); 66 | 67 | int? batchLimit = this.serverConfig.Value.BatchRequestLimit; 68 | List responses = new List(); 69 | if (batchLimit > 0 && result.RequestCount > batchLimit) 70 | { 71 | string batchLimitError = $"Request count exceeded batch request limit ({batchLimit})."; 72 | responses = new List 73 | { 74 | new RpcResponse(new RpcId(), new RpcError(RpcErrorCode.InvalidRequest, batchLimitError)) 75 | }; 76 | this.logger.LogError(batchLimitError + " Returning error response."); 77 | } 78 | else 79 | { 80 | if (result.Requests.Any()) 81 | { 82 | responses = await this.invoker.InvokeBatchRequestAsync(result.Requests); 83 | } 84 | else 85 | { 86 | responses = new List(); 87 | } 88 | foreach ((RpcId id, RpcError error) in result.Errors) 89 | { 90 | if (id == default && error.Code != -32600) 91 | { 92 | // Dont sent response if there is no id AND the error 93 | // is NOT 'Invalid Request' 94 | this.logger.ResponseFailedWithNoId(error.Code, error.Message); 95 | continue; 96 | } 97 | responses.Add(new RpcResponse(id, error)); 98 | } 99 | } 100 | if (responses == null || !responses.Any()) 101 | { 102 | this.logger.NoResponses(); 103 | return false; 104 | } 105 | this.logger.Responses(responses.Count); 106 | 107 | if (result.IsBulkRequest) 108 | { 109 | await this.responseSerializer.SerializeBulkAsync(responses, responseBody); 110 | } 111 | else 112 | { 113 | await this.responseSerializer.SerializeAsync(responses.Single(), responseBody); 114 | } 115 | } 116 | catch (RpcException ex) 117 | { 118 | this.logger.LogException(ex, "Error occurred when proccessing Rpc request. Sending Rpc error response"); 119 | var response = new RpcResponse(new RpcId(), ex.ToRpcError(this.serverConfig.Value.ShowServerExceptions)); 120 | await this.responseSerializer.SerializeAsync(response, responseBody); 121 | } 122 | return true; 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /test/EdjCase.JsonRpc.Router.Sample/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using EdjCase.JsonRpc.Router.Defaults; 6 | using Microsoft.AspNetCore; 7 | using System.Reflection; 8 | using System.Text.Json; 9 | using EdjCase.JsonRpc.Router.Swagger.Extensions; 10 | using Microsoft.Extensions.Configuration; 11 | using System.Text.Json.Serialization; 12 | using EdjCase.JsonRpc.Router.Sample.Controllers; 13 | 14 | namespace EdjCase.JsonRpc.Router.Sample 15 | { 16 | public class Startup 17 | { 18 | private readonly IConfiguration configuration; 19 | 20 | public Startup(IConfiguration configuration) 21 | { 22 | this.configuration = configuration; 23 | } 24 | 25 | // This method gets called by a runtime. 26 | // Use this method to add services to the container 27 | public void ConfigureServices(IServiceCollection services) 28 | { 29 | var globalJsonSerializerOptions = new JsonSerializerOptions 30 | { 31 | //Example json config 32 | DefaultIgnoreCondition = JsonIgnoreCondition.Never, 33 | WriteIndented = true 34 | }; 35 | void ConfigureRpc(RpcServerConfiguration config) 36 | { 37 | //(Optional) Hard cap on batch size, will block requests will larger sizes, defaults to no limit 38 | config.BatchRequestLimit = 5; 39 | //(Optional) If true returns full error messages in response, defaults to false 40 | config.ShowServerExceptions = false; 41 | //(Optional) Configure how the router serializes requests 42 | config.JsonSerializerSettings = globalJsonSerializerOptions; 43 | //(Optional) Configure custom exception handling for exceptions during invocation of the method 44 | config.OnInvokeException = (context) => 45 | { 46 | if (context.Exception is InvalidOperationException) 47 | { 48 | //Handle a certain type of exception and return a custom response instead 49 | //of an internal server error 50 | int customErrorCode = 1; 51 | var customData = new 52 | { 53 | Field = "Value" 54 | }; 55 | var response = new RpcMethodErrorResult(customErrorCode, "Custom message", customData); 56 | return OnExceptionResult.UseObjectResponse(response); 57 | } 58 | //Continue to throw the exception 59 | return OnExceptionResult.DontHandle(); 60 | }; 61 | } 62 | 63 | 64 | services 65 | .AddControllers() 66 | .Services 67 | .AddJsonRpcWithSwagger(ConfigureRpc, globalJsonSerializerOptions) 68 | .Configure(options => 69 | { 70 | options.SizeLimit = 10; 71 | options.SlidingExpiration = TimeSpan.FromMinutes(5); 72 | options.AbsoluteExpiration = TimeSpan.FromMinutes(90); 73 | }); 74 | } 75 | 76 | 77 | 78 | // Configure is called after ConfigureServices is called. 79 | public void Configure(IApplicationBuilder app) 80 | { 81 | app 82 | .Map("/Mix", b => 83 | { 84 | b 85 | .UseRouting() 86 | .UseEndpoints(endpoints => 87 | { 88 | endpoints.MapControllers(); 89 | }) 90 | .UseJsonRpc(b => 91 | { 92 | b.AddController(); 93 | }); 94 | }) 95 | .Map("/BaseController", b => 96 | { 97 | //Will make all controllers that derived from `ControllerBase` available 98 | //Each dervied controller will use their name as the route, unless overridden by RpcRouteAttribute 99 | b.UseJsonRpcWithBaseController(); 100 | }) 101 | .Map("/Controllers", b => 102 | { 103 | b.UseJsonRpc(options => 104 | { 105 | options 106 | //Will make controller methods available for path '/First', unless overridden by RpcRouteAttribute 107 | //Not that any class will work here, not just a class derived from `RpcController` 108 | .AddController() 109 | //Will make `CustomController` methods available for custom path '/CustomPath' 110 | .AddControllerWithCustomPath("CustomPath"); 111 | }); 112 | }) 113 | .Map("/Methods", b => 114 | { 115 | b.UseJsonRpc(options => 116 | { 117 | MethodInfo customControllerMethod1 = typeof(CustomController).GetMethod("Method1"); 118 | MethodInfo otherControllerMethod1 = typeof(OtherController).GetMethod("Method1"); 119 | options 120 | //Will make the `Method1` method in `CustomController` available with route '/' 121 | //Note that since that method has `RpcRouteAttribute("Method")`, that will change the method name 122 | //from `Method1` to `Method` in the router 123 | .AddMethod(customControllerMethod1) 124 | //Will make the `Method1` method in `OtherController` available with route '/CustomMethods' 125 | .AddMethod(otherControllerMethod1, "CustomMethods"); 126 | }); 127 | 128 | }) 129 | //Will make all public classes deriving from `RpcController` available to the rpc router 130 | .UseJsonRpcWithSwaggerUI(); 131 | 132 | } 133 | } 134 | 135 | public class Program 136 | { 137 | public static void Main(string[] args) 138 | { 139 | var host = WebHost.CreateDefaultBuilder(args) 140 | .UseStartup() 141 | .Build(); 142 | 143 | host.Run(); 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /test/Benchmarks/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Security.Claims; 6 | using BenchmarkDotNet.Analysers; 7 | using BenchmarkDotNet.Attributes; 8 | using BenchmarkDotNet.Configs; 9 | using BenchmarkDotNet.Engines; 10 | using BenchmarkDotNet.Running; 11 | using EdjCase.JsonRpc.Router; 12 | using EdjCase.JsonRpc.Router.Abstractions; 13 | using EdjCase.JsonRpc.Router.Defaults; 14 | using Microsoft.Extensions.Logging; 15 | using Microsoft.Extensions.Options; 16 | 17 | namespace Benchmarks 18 | { 19 | public class Program 20 | { 21 | public static void Main() 22 | { 23 | //var tester = new RequestMatcherTester(); 24 | //tester.GlobalSetup(); 25 | //tester.SimpleIterationSetup(); 26 | //Type type = typeof(Program); 27 | //for (int i = 0; i < 100_000; i++) 28 | //{ 29 | // tester.SimpleParamsNoReturn(); 30 | //} 31 | _ = BenchmarkRunner.Run(); 32 | } 33 | 34 | #pragma warning disable CA1822 // Mark members as static 35 | public void Test() 36 | #pragma warning restore CA1822 // Mark members as static 37 | { 38 | 39 | } 40 | } 41 | 42 | [MValueColumn] 43 | [MemoryDiagnoser] 44 | [SimpleJob(RunStrategy.Throughput, invocationCount: 100_000)] 45 | public class RequestMatcherTester 46 | { 47 | private IRpcRequestMatcher? requestMatcher; 48 | 49 | [GlobalSetup] 50 | public void GlobalSetup() 51 | { 52 | var logger = new FakeLogger(); 53 | var methodProvider = new FakeMethodProvider(); 54 | var fakeRpcContextAccessor = new FakeRpcContextAccessor(); 55 | var options = Options.Create(new RpcServerConfiguration 56 | { 57 | JsonSerializerSettings = null 58 | }); 59 | var rpcParameterConverter = new DefaultRpcParameterConverter(options, new FakeLogger()); 60 | this.requestMatcher = new DefaultRequestMatcher( 61 | logger, 62 | methodProvider, 63 | fakeRpcContextAccessor, 64 | rpcParameterConverter, 65 | new RequestMatcherCache(Options.Create(new RequestCacheOptions())) 66 | ); 67 | } 68 | 69 | private RpcRequestSignature? requestsignature; 70 | 71 | [IterationSetup(Target = nameof(NoParamsNoReturn))] 72 | public void IterationSetup() 73 | { 74 | this.requestsignature = RpcRequestSignature.Create(nameof(MethodClass.NoParamsNoReturn)); 75 | } 76 | 77 | [Benchmark] 78 | public void NoParamsNoReturn() 79 | { 80 | _ = this.requestMatcher!.GetMatchingMethod(this.requestsignature!); 81 | } 82 | 83 | [IterationSetup(Target = nameof(ComplexParamNoReturn))] 84 | public void ComplexIterationSetup() 85 | { 86 | this.requestsignature = RpcRequestSignature.Create(nameof(MethodClass.ComplexParamNoReturn), new[] { RpcParameterType.Object }); 87 | } 88 | 89 | [Benchmark] 90 | public void ComplexParamNoReturn() 91 | { 92 | _ = this.requestMatcher!.GetMatchingMethod(this.requestsignature!); 93 | } 94 | 95 | 96 | [IterationSetup(Target = nameof(SimpleParamsNoReturn))] 97 | public void SimpleIterationSetup() 98 | { 99 | var parameters = new Dictionary 100 | { 101 | {"a", RpcParameterType.Number }, 102 | {"b", RpcParameterType.Boolean }, 103 | {"c", RpcParameterType.String } 104 | }; 105 | this.requestsignature = RpcRequestSignature.Create(nameof(MethodClass.SimpleParamsNoReturn), parameters); 106 | } 107 | 108 | [Benchmark] 109 | public void SimpleParamsNoReturn() 110 | { 111 | _ = this.requestMatcher!.GetMatchingMethod(this.requestsignature!); 112 | } 113 | 114 | 115 | #pragma warning disable IDE0060 // Remove unused parameter 116 | internal class MethodClass 117 | { 118 | public void NoParamsNoReturn() 119 | { 120 | 121 | } 122 | public void ComplexParamNoReturn(ComplexParam complex) 123 | { 124 | 125 | } 126 | 127 | public void SimpleParamsNoReturn(int a, bool b, string c) 128 | { 129 | 130 | } 131 | 132 | public class ComplexParam 133 | { 134 | public string? A { get; set; } 135 | public bool B { get; set; } 136 | public ComplexParam? C { get; set; } 137 | } 138 | } 139 | #pragma warning restore IDE0060 // Remove unused parameter 140 | } 141 | 142 | public class FakeRpcContextAccessor : IRpcContextAccessor 143 | { 144 | 145 | public RpcContext Get() 146 | { 147 | #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. 148 | return new RpcContext(null, "/api/v1/controller_name"); 149 | #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. 150 | } 151 | 152 | public void Set(RpcContext context) 153 | { 154 | throw new NotImplementedException(); 155 | } 156 | } 157 | 158 | internal class FakeMethodProvider : IRpcMethodProvider 159 | { 160 | private static readonly List methods = typeof(RequestMatcherTester.MethodClass) 161 | .GetTypeInfo() 162 | .GetMethods(BindingFlags.Public | BindingFlags.Instance) 163 | .Where(m => m.DeclaringType != typeof(object)) 164 | .Select(DefaultRpcMethodInfo.FromMethodInfo) 165 | .ToList(); 166 | 167 | 168 | public RpcRouteMetaData Get() 169 | { 170 | return new RpcRouteMetaData(FakeMethodProvider.methods, new Dictionary>()); 171 | } 172 | } 173 | 174 | public class FakeLogger : ILogger 175 | { 176 | public IDisposable? BeginScope(TState state) where TState : notnull 177 | { 178 | return new FakeDisposable(); 179 | } 180 | 181 | public bool IsEnabled(LogLevel logLevel) 182 | { 183 | return false; 184 | } 185 | 186 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) 187 | { 188 | 189 | } 190 | 191 | private class FakeDisposable : IDisposable 192 | { 193 | public void Dispose() 194 | { 195 | 196 | } 197 | } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /EdjCase.JsonRpc.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33103.184 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EB6CC2D7-ED2C-447F-A85B-5E204FD69352}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{41AD7143-8434-4ABE-92B7-70F448CFE634}" 9 | ProjectSection(SolutionItems) = preProject 10 | .editorconfig = .editorconfig 11 | Nuget.config = Nuget.config 12 | EndProjectSection 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{B5DD29D3-4FCA-4CFB-A562-A7985BB1C269}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdjCase.JsonRpc.Router", "src\EdjCase.JsonRpc.Router\EdjCase.JsonRpc.Router.csproj", "{F89E9E51-0D7A-4A82-A899-14C886C4F384}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdjCase.JsonRpc.Router.Sample", "test\EdjCase.JsonRpc.Router.Sample\EdjCase.JsonRpc.Router.Sample.csproj", "{DC822B36-8944-48E5-AFC3-B6F859F49E02}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdjCase.JsonRpc.Router.Tests", "test\EdjCase.JsonRpc.Router.Tests\EdjCase.JsonRpc.Router.Tests.csproj", "{EB3C5DC1-9E22-4C56-8E1F-0D93917E75E5}" 21 | EndProject 22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdjCase.JsonRpc.Client", "src\EdjCase.JsonRpc.Client\EdjCase.JsonRpc.Client.csproj", "{87ED8B44-B59A-440C-A377-565EFFB2691A}" 23 | EndProject 24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdjCase.JsonRpc.Client.Sample", "test\EdjCase.JsonRpc.Client.Sample\EdjCase.JsonRpc.Client.Sample.csproj", "{84727B1C-6DED-4460-903B-27B19F1326AC}" 25 | EndProject 26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdjCase.JsonRpc.Client.Tests", "test\EdjCase.JsonRpc.Client.Tests\EdjCase.JsonRpc.Client.Tests.csproj", "{C793BB58-9D77-401E-92F8-3BF81AA5B34C}" 27 | EndProject 28 | Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "EdjCase.JsonRpc.Common", "src\EdjCase.JsonRpc.Common\EdjCase.JsonRpc.Common.shproj", "{1546452E-2DB4-421C-90CD-B4B310CE9AD9}" 29 | EndProject 30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Benchmarks", "test\Benchmarks\Benchmarks.csproj", "{08608574-6625-40D4-85EC-953B1E889A5B}" 31 | EndProject 32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdjCase.JsonRpc.Router.Swagger", "src\EdjCase.JsonRpc.Router.Swagger\EdjCase.JsonRpc.Router.Swagger.csproj", "{93369553-1DA3-47A1-B46B-23858B68099D}" 33 | EndProject 34 | Global 35 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 36 | Debug|Any CPU = Debug|Any CPU 37 | Release|Any CPU = Release|Any CPU 38 | EndGlobalSection 39 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 40 | {F89E9E51-0D7A-4A82-A899-14C886C4F384}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {F89E9E51-0D7A-4A82-A899-14C886C4F384}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {F89E9E51-0D7A-4A82-A899-14C886C4F384}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {F89E9E51-0D7A-4A82-A899-14C886C4F384}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {DC822B36-8944-48E5-AFC3-B6F859F49E02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {DC822B36-8944-48E5-AFC3-B6F859F49E02}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {DC822B36-8944-48E5-AFC3-B6F859F49E02}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {DC822B36-8944-48E5-AFC3-B6F859F49E02}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {EB3C5DC1-9E22-4C56-8E1F-0D93917E75E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {EB3C5DC1-9E22-4C56-8E1F-0D93917E75E5}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {EB3C5DC1-9E22-4C56-8E1F-0D93917E75E5}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {EB3C5DC1-9E22-4C56-8E1F-0D93917E75E5}.Release|Any CPU.Build.0 = Release|Any CPU 52 | {87ED8B44-B59A-440C-A377-565EFFB2691A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {87ED8B44-B59A-440C-A377-565EFFB2691A}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {87ED8B44-B59A-440C-A377-565EFFB2691A}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {87ED8B44-B59A-440C-A377-565EFFB2691A}.Release|Any CPU.Build.0 = Release|Any CPU 56 | {84727B1C-6DED-4460-903B-27B19F1326AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 57 | {84727B1C-6DED-4460-903B-27B19F1326AC}.Debug|Any CPU.Build.0 = Debug|Any CPU 58 | {84727B1C-6DED-4460-903B-27B19F1326AC}.Release|Any CPU.ActiveCfg = Release|Any CPU 59 | {84727B1C-6DED-4460-903B-27B19F1326AC}.Release|Any CPU.Build.0 = Release|Any CPU 60 | {C793BB58-9D77-401E-92F8-3BF81AA5B34C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 61 | {C793BB58-9D77-401E-92F8-3BF81AA5B34C}.Debug|Any CPU.Build.0 = Debug|Any CPU 62 | {C793BB58-9D77-401E-92F8-3BF81AA5B34C}.Release|Any CPU.ActiveCfg = Release|Any CPU 63 | {C793BB58-9D77-401E-92F8-3BF81AA5B34C}.Release|Any CPU.Build.0 = Release|Any CPU 64 | {08608574-6625-40D4-85EC-953B1E889A5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 65 | {08608574-6625-40D4-85EC-953B1E889A5B}.Debug|Any CPU.Build.0 = Debug|Any CPU 66 | {08608574-6625-40D4-85EC-953B1E889A5B}.Release|Any CPU.ActiveCfg = Release|Any CPU 67 | {08608574-6625-40D4-85EC-953B1E889A5B}.Release|Any CPU.Build.0 = Release|Any CPU 68 | {93369553-1DA3-47A1-B46B-23858B68099D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 69 | {93369553-1DA3-47A1-B46B-23858B68099D}.Debug|Any CPU.Build.0 = Debug|Any CPU 70 | {93369553-1DA3-47A1-B46B-23858B68099D}.Release|Any CPU.ActiveCfg = Release|Any CPU 71 | {93369553-1DA3-47A1-B46B-23858B68099D}.Release|Any CPU.Build.0 = Release|Any CPU 72 | EndGlobalSection 73 | GlobalSection(SolutionProperties) = preSolution 74 | HideSolutionNode = FALSE 75 | EndGlobalSection 76 | GlobalSection(NestedProjects) = preSolution 77 | {F89E9E51-0D7A-4A82-A899-14C886C4F384} = {EB6CC2D7-ED2C-447F-A85B-5E204FD69352} 78 | {DC822B36-8944-48E5-AFC3-B6F859F49E02} = {B5DD29D3-4FCA-4CFB-A562-A7985BB1C269} 79 | {EB3C5DC1-9E22-4C56-8E1F-0D93917E75E5} = {B5DD29D3-4FCA-4CFB-A562-A7985BB1C269} 80 | {87ED8B44-B59A-440C-A377-565EFFB2691A} = {EB6CC2D7-ED2C-447F-A85B-5E204FD69352} 81 | {84727B1C-6DED-4460-903B-27B19F1326AC} = {B5DD29D3-4FCA-4CFB-A562-A7985BB1C269} 82 | {C793BB58-9D77-401E-92F8-3BF81AA5B34C} = {B5DD29D3-4FCA-4CFB-A562-A7985BB1C269} 83 | {1546452E-2DB4-421C-90CD-B4B310CE9AD9} = {EB6CC2D7-ED2C-447F-A85B-5E204FD69352} 84 | {08608574-6625-40D4-85EC-953B1E889A5B} = {B5DD29D3-4FCA-4CFB-A562-A7985BB1C269} 85 | {93369553-1DA3-47A1-B46B-23858B68099D} = {EB6CC2D7-ED2C-447F-A85B-5E204FD69352} 86 | EndGlobalSection 87 | GlobalSection(ExtensibilityGlobals) = postSolution 88 | SolutionGuid = {297BE26F-B61D-4A43-9A84-2442133FD45E} 89 | EndGlobalSection 90 | GlobalSection(SharedMSBuildProjectFiles) = preSolution 91 | src\EdjCase.JsonRpc.Common\EdjCase.JsonRpc.Common.projitems*{1546452e-2db4-421c-90cd-b4b310ce9ad9}*SharedItemsImports = 13 92 | src\EdjCase.JsonRpc.Common\EdjCase.JsonRpc.Common.projitems*{87ed8b44-b59a-440c-a377-565effb2691a}*SharedItemsImports = 5 93 | src\EdjCase.JsonRpc.Common\EdjCase.JsonRpc.Common.projitems*{f89e9e51-0d7a-4a82-a899-14c886c4f384}*SharedItemsImports = 5 94 | EndGlobalSection 95 | EndGlobal 96 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/RpcPath.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace EdjCase.JsonRpc.Router 7 | { 8 | /// 9 | /// Represents the url path for Rpc routing purposes 10 | /// 11 | public class RpcPath : IEquatable 12 | { 13 | private char[] path; 14 | 15 | private int? hashCodeCache; 16 | 17 | private RpcPath(char[] path) 18 | { 19 | if (path == null || path.Length < 1) 20 | { 21 | throw new ArgumentNullException(nameof(path)); 22 | } 23 | this.path = path; 24 | } 25 | 26 | public static bool operator ==(RpcPath? path1, RpcPath? path2) 27 | { 28 | if (object.ReferenceEquals(path1, null)) 29 | { 30 | return object.ReferenceEquals(path2, null); 31 | } 32 | return path1.Equals(path2); 33 | } 34 | 35 | public static bool operator !=(RpcPath? path1, RpcPath? path2) 36 | { 37 | return !(path1 == path2); 38 | } 39 | 40 | public bool StartsWith(RpcPath? other) 41 | { 42 | if (other == null) 43 | { 44 | return true; 45 | } 46 | if (other.path.Length > this.path.Length) 47 | { 48 | return false; 49 | } 50 | for (int i = 0; i < other.path.Length; i++) 51 | { 52 | if (other.path[i] != this.path[i]) 53 | { 54 | return false; 55 | } 56 | } 57 | return true; 58 | } 59 | 60 | public bool Equals(RpcPath? other) 61 | { 62 | if (object.ReferenceEquals(other, null)) 63 | { 64 | return false; 65 | } 66 | return this.GetHashCode() == other.GetHashCode(); 67 | } 68 | 69 | 70 | public override bool Equals(object? obj) 71 | { 72 | if (obj is RpcPath path) 73 | { 74 | return this.Equals(path); 75 | } 76 | return false; 77 | } 78 | 79 | 80 | public override int GetHashCode() 81 | { 82 | //TODO best way to optimize gethashcode? multithread? 83 | if (this.hashCodeCache == null) 84 | { 85 | int hash = 1337; 86 | foreach (char component in this.path) 87 | { 88 | hash = (hash * 7) + component.GetHashCode(); 89 | } 90 | 91 | this.hashCodeCache = hash; 92 | } 93 | return this.hashCodeCache.Value; 94 | } 95 | 96 | /// 97 | /// Creates a based on the string form of the path 98 | /// 99 | /// Uri/route path 100 | /// Rpc path based on the path string 101 | public static RpcPath Parse(ReadOnlySpan path) 102 | { 103 | if (!RpcPath.TryParse(path, out RpcPath? rpcPath)) 104 | { 105 | throw new RpcException(RpcErrorCode.ParseError, $"Rpc path could not be parsed from '{new string(path.ToArray())}'."); 106 | } 107 | return rpcPath!; 108 | } 109 | /// 110 | /// Creates a based on the string form of the path 111 | /// 112 | /// Uri/route path 113 | /// True if the path parses, otherwise false 114 | public static bool TryParse(ReadOnlySpan path, out RpcPath? rpcPath) 115 | { 116 | if (path.IsEmpty) 117 | { 118 | rpcPath = null; 119 | return true; 120 | } 121 | else 122 | { 123 | try 124 | { 125 | int start = IsSlash(path[0]) ? 1 : 0; 126 | if (path.Length <= start) 127 | { 128 | rpcPath = default; 129 | return true; 130 | } 131 | int length = IsSlash(path[path.Length - 1]) ? path.Length - 1 : path.Length; 132 | if (start >= length - 1) 133 | { 134 | rpcPath = default; 135 | return true; 136 | } 137 | 138 | 139 | var charArray = new char[length - start]; 140 | 141 | int j = 0; 142 | for (int i = start; i < length; i++) 143 | { 144 | char c; 145 | if (char.IsWhiteSpace(path[i])) 146 | { 147 | rpcPath = default; 148 | return false; 149 | } 150 | else if (IsSlash(path[i])) 151 | { 152 | //make all the slashes the same 153 | c = '/'; 154 | } 155 | else 156 | { 157 | c = char.ToLowerInvariant(path[i]); 158 | } 159 | 160 | charArray[j] = c; 161 | j++; 162 | } 163 | rpcPath = new RpcPath(charArray); 164 | return true; 165 | } 166 | catch 167 | { 168 | rpcPath = default; 169 | return false; 170 | } 171 | } 172 | bool IsSlash(char c) 173 | { 174 | return c == '/' || c == '\\'; 175 | } 176 | } 177 | 178 | /// 179 | /// Removes the base path path from this path 180 | /// 181 | /// Base path to remove 182 | /// A new path that is the full path without the base path 183 | public RpcPath? RemoveBasePath(RpcPath basePath) 184 | { 185 | if (!this.TryRemoveBasePath(basePath, out RpcPath? path)) 186 | { 187 | throw new RpcException(RpcErrorCode.ParseError, $"Count not remove path '{basePath}' from path '{this}'."); 188 | } 189 | return path; 190 | } 191 | 192 | /// 193 | /// Tries to remove the base path path from this path 194 | /// 195 | /// Base path to remove 196 | /// True if removed the base path. Otherwise false 197 | public bool TryRemoveBasePath(RpcPath? basePath, out RpcPath? path) 198 | { 199 | if (basePath == null) 200 | { 201 | path = this.Clone(); 202 | return true; 203 | } 204 | if (!this.StartsWith(basePath)) 205 | { 206 | path = default; 207 | return false; 208 | } 209 | int size = this.path.Length - basePath.path.Length; 210 | if (size < 1) 211 | { 212 | path = default; 213 | return true; 214 | } 215 | //Removes the / as well 216 | var newComponents = new char[size - 1]; 217 | this.path.AsSpan(basePath.path.Length + 1).CopyTo(newComponents); 218 | path = new RpcPath(newComponents); 219 | return true; 220 | } 221 | 222 | /// 223 | /// Merges the two paths to create a new Rpc path that is the combination of the two 224 | /// 225 | /// Other path to add to the end of the current path 226 | /// A new path that is the combination of the two paths 227 | public RpcPath Add(RpcPath other) 228 | { 229 | if (other == null) 230 | { 231 | return this.Clone(); 232 | } 233 | char[] newComponents = new char[this.path.Length + other.path.Length + 1]; 234 | this.path.CopyTo(newComponents, 0); 235 | newComponents[this.path.Length] = '/'; 236 | other.path.CopyTo(newComponents, this.path.Length + 1); 237 | return new RpcPath(newComponents); 238 | } 239 | 240 | public override string ToString() 241 | { 242 | return new string(this.path); 243 | } 244 | 245 | public RpcPath Clone() 246 | { 247 | var newComponents = new char[this.path.Length]; 248 | this.path.CopyTo(newComponents, 0); 249 | return new RpcPath(newComponents); 250 | } 251 | 252 | public static implicit operator string?(RpcPath path) 253 | { 254 | return path?.ToString(); 255 | } 256 | 257 | public static implicit operator RpcPath(string s) 258 | { 259 | return RpcPath.Parse(s.AsSpan()); 260 | } 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Router/BuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using EdjCase.JsonRpc.Router; 3 | using EdjCase.JsonRpc.Router.Abstractions; 4 | using EdjCase.JsonRpc.Router.Defaults; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Options; 7 | using Microsoft.Extensions.DependencyInjection.Extensions; 8 | using EdjCase.JsonRpc.Common.Tools; 9 | using System.Collections.Generic; 10 | using System.Reflection; 11 | using System.Linq; 12 | 13 | // ReSharper disable once CheckNamespace 14 | namespace Microsoft.AspNetCore.Builder 15 | { 16 | /// 17 | /// Extension class to add JsonRpc router to Asp.Net pipeline 18 | /// 19 | public static class BuilderExtensions 20 | { 21 | /// 22 | /// Extension method to add the JsonRpc router services to the IoC container 23 | /// 24 | /// IoC serivce container to register JsonRpc dependencies 25 | /// Configuration action for server wide rpc configuration 26 | /// IoC service container 27 | public static IServiceCollection AddJsonRpc(this IServiceCollection serviceCollection, Action? configureOptions) 28 | { 29 | var configuration = new RpcServerConfiguration(); 30 | configureOptions?.Invoke(configuration); 31 | return serviceCollection.AddJsonRpc(configuration); 32 | } 33 | 34 | /// 35 | /// Extension method to add the JsonRpc router services to the IoC container 36 | /// 37 | /// IoC serivce container to register JsonRpc dependencies 38 | /// (Optional) Server wide rpc configuration 39 | /// IoC service container 40 | public static IServiceCollection AddJsonRpc( 41 | this IServiceCollection serviceCollection, 42 | RpcServerConfiguration? configuration = null 43 | ) 44 | { 45 | if (serviceCollection == null) 46 | { 47 | throw new ArgumentNullException(nameof(serviceCollection)); 48 | } 49 | if (configuration == null) 50 | { 51 | configuration = new RpcServerConfiguration(); 52 | } 53 | serviceCollection.AddSingleton(new RpcServicesMarker()); 54 | serviceCollection 55 | .TryAddScoped(); 56 | serviceCollection 57 | .TryAddScoped(); 58 | serviceCollection 59 | .TryAddScoped(); 60 | if (configuration.UseCompression) 61 | { 62 | serviceCollection 63 | .TryAddScoped(); 64 | } 65 | serviceCollection 66 | .TryAddScoped(); 67 | serviceCollection 68 | .TryAddScoped(); 69 | serviceCollection 70 | .TryAddSingleton(); 71 | serviceCollection 72 | .AddOptions(); 73 | serviceCollection 74 | .TryAddScoped(); 75 | serviceCollection 76 | .TryAddScoped(); 77 | serviceCollection 78 | .TryAddScoped(); 79 | serviceCollection 80 | .TryAddScoped(); 81 | serviceCollection 82 | .TryAddSingleton(); 83 | serviceCollection.AddHttpContextAccessor(); 84 | 85 | 86 | return serviceCollection 87 | .AddSingleton(Options.Create(configuration)) 88 | .AddRouting() 89 | .AddAuthorizationCore(); 90 | } 91 | 92 | /// 93 | /// Extension method to use the JsonRpc router in the Asp.Net pipeline 94 | /// 95 | /// that is supplied by Asp.Net 96 | /// (Optional) Action to configure the endpoints. Will default to include all controllers that derive from `RpcController` 97 | /// that includes the Basic auth middleware 98 | public static IApplicationBuilder UseJsonRpc(this IApplicationBuilder app, Action? builder = null) 99 | { 100 | if (app == null) 101 | { 102 | throw new ArgumentNullException(nameof(app)); 103 | } 104 | 105 | var options = new RpcEndpointBuilder(); 106 | builder = builder ?? BuildFromBaseController; 107 | builder.Invoke(options); 108 | RpcRouteMetaData data = options.Resolve(); 109 | return app.UseJsonRpc(data); 110 | } 111 | 112 | /// 113 | /// Extension method to use the JsonRpc router in the Asp.Net pipeline 114 | /// Uses all the public methods on controllers extending the specified class 115 | /// 116 | /// that is supplied by Asp.Net 117 | /// that includes the Basic auth middleware 118 | public static IApplicationBuilder UseJsonRpcWithBaseController(this IApplicationBuilder app) 119 | { 120 | if (app == null) 121 | { 122 | throw new ArgumentNullException(nameof(app)); 123 | } 124 | 125 | return app.UseJsonRpc(BuildFromBaseController); 126 | } 127 | 128 | private static void BuildFromBaseController(RpcEndpointBuilder builder) 129 | { 130 | Type baseControllerType = typeof(T); 131 | IEnumerable controllers = Assembly 132 | .GetEntryAssembly()! 133 | .GetReferencedAssemblies() 134 | .Select(Assembly.Load) 135 | .SelectMany(x => x.DefinedTypes) 136 | .Concat(Assembly.GetEntryAssembly()!.DefinedTypes) 137 | .Where(t => !t.IsAbstract && (t == baseControllerType || t.IsSubclassOf(baseControllerType))); 138 | 139 | foreach (Type type in controllers) 140 | { 141 | builder.AddController(type); 142 | } 143 | } 144 | 145 | /// 146 | /// Extension method to use the JsonRpc router in the Asp.Net pipeline 147 | /// 148 | /// that is supplied by Asp.Net 149 | /// All the available methods to call 150 | /// that includes the Basic auth middleware 151 | internal static IApplicationBuilder UseJsonRpc(this IApplicationBuilder app, RpcRouteMetaData data) 152 | { 153 | if (app == null) 154 | { 155 | throw new ArgumentNullException(nameof(app)); 156 | } 157 | if (data == null) 158 | { 159 | throw new ArgumentNullException(nameof(data)); 160 | } 161 | if (app.ApplicationServices.GetService() == null) 162 | { 163 | throw new InvalidOperationException("AddJsonRpc() needs to be called in the ConfigureServices method."); 164 | } 165 | var router = new RpcHttpRouter(); 166 | app.ApplicationServices.GetRequiredService().Value = data; 167 | return app.UseRouter(router); 168 | } 169 | 170 | 171 | } 172 | 173 | internal class RpcServicesMarker 174 | { 175 | 176 | } 177 | } -------------------------------------------------------------------------------- /src/EdjCase.JsonRpc.Client/DefaultRequestSerializer.cs: -------------------------------------------------------------------------------- 1 | using EdjCase.JsonRpc.Common; 2 | using Newtonsoft.Json; 3 | using Newtonsoft.Json.Linq; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | 10 | namespace EdjCase.JsonRpc.Client 11 | { 12 | internal interface IRequestSerializer 13 | { 14 | string SerializeBulk(IList requests); 15 | string Serialize(RpcRequest request); 16 | List Deserialize(string json, IDictionary typeMap); 17 | } 18 | 19 | 20 | public class DefaultRequestJsonSerializer : IRequestSerializer 21 | { 22 | private JsonSerializerSettings? jsonSerializerSettings { get; } 23 | private IDictionary? errorTypes { get; } 24 | internal DefaultRequestJsonSerializer( 25 | JsonSerializerSettings? jsonSerializerSettings = null, 26 | IDictionary? errorTypes = null) 27 | { 28 | this.jsonSerializerSettings = jsonSerializerSettings; 29 | this.errorTypes = errorTypes; 30 | } 31 | 32 | public List Deserialize(string json, IDictionary typeMap) 33 | { 34 | using TextReader textReader = new StringReader(json); 35 | using JsonReader reader = new JsonTextReader(textReader) 36 | { 37 | //Prevent auto date parsing 38 | DateParseHandling = DateParseHandling.None 39 | }; 40 | 41 | List responses; 42 | JToken token = JToken.Load(reader); 43 | switch (token.Type) 44 | { 45 | case JTokenType.Array: 46 | responses = token.Select(Deserialize).ToList(); 47 | RpcResponse Deserialize(JToken t) 48 | { 49 | return this.DeserializeResponse(t, typeMap); 50 | } 51 | break; 52 | case JTokenType.Object: 53 | RpcResponse response = this.DeserializeResponse(token, typeMap); 54 | responses = new List { response }; 55 | break; 56 | default: 57 | throw new ArgumentOutOfRangeException(nameof(token.Type)); 58 | } 59 | return responses; 60 | } 61 | 62 | public RpcResponse DeserializeResponse(JToken token, IDictionary typeMap) 63 | { 64 | JToken? idToken = token[JsonRpcContants.IdPropertyName]; 65 | if (idToken == null) 66 | { 67 | throw new RpcClientParseException("Unable to parse request id."); 68 | } 69 | RpcId id; 70 | switch (idToken.Type) 71 | { 72 | case JTokenType.Null: 73 | id = new RpcId(); 74 | break; 75 | case JTokenType.Integer: 76 | id = new RpcId(idToken.Value()!); 77 | break; 78 | case JTokenType.String: 79 | case JTokenType.Guid: 80 | id = new RpcId(idToken.Value()!); 81 | break; 82 | default: 83 | throw new RpcClientParseException("Unable to parse rpc id as string or integer."); 84 | } 85 | if(!typeMap.TryGetValue(id, out Type? type) || type == null) 86 | { 87 | throw new RpcClientParseException("Unable to detect result type, cannot deserialize."); 88 | } 89 | JToken? errorToken = token[JsonRpcContants.ErrorPropertyName]; 90 | if (errorToken != null && errorToken.HasValues) 91 | { 92 | int code = errorToken.Value(JsonRpcContants.ErrorCodePropertyName); 93 | string message = errorToken.Value(JsonRpcContants.ErrorMessagePropertyName)!; 94 | JToken? dataToken = errorToken[JsonRpcContants.ErrorDataPropertyName]; 95 | 96 | object? data = null; 97 | if (dataToken != null) 98 | { 99 | if (this.errorTypes != null && this.errorTypes.TryGetValue(code, out Type? errorCodeType) && errorCodeType != null) 100 | { 101 | data = dataToken.ToObject(errorCodeType); 102 | } 103 | else 104 | { 105 | data = dataToken.ToString(); 106 | } 107 | } 108 | var error = new RpcError(code, message, data: data); 109 | return new RpcResponse(id, error); 110 | } 111 | else 112 | { 113 | object? result; 114 | if (this.jsonSerializerSettings == null) 115 | { 116 | result = token[JsonRpcContants.ResultPropertyName]?.ToObject(type); 117 | } 118 | else 119 | { 120 | //TODo cache serializer? 121 | JsonSerializer serializer = JsonSerializer.Create(this.jsonSerializerSettings); 122 | result = token[JsonRpcContants.ResultPropertyName]?.ToObject(type, serializer); 123 | } 124 | return new RpcResponse(id, result); 125 | } 126 | } 127 | 128 | public string Serialize(RpcRequest request) 129 | { 130 | return this.SerializeInternal(new[] { request }, isBulkRequest: false); 131 | } 132 | 133 | public string SerializeBulk(IList requests) 134 | { 135 | return this.SerializeInternal(requests, isBulkRequest: true); 136 | } 137 | 138 | private string SerializeInternal(IEnumerable requests, bool isBulkRequest) 139 | { 140 | using StringWriter textWriter = new StringWriter(); 141 | using (JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)) 142 | { 143 | if (isBulkRequest) 144 | { 145 | jsonWriter.WriteStartArray(); 146 | foreach (RpcRequest request in requests) 147 | { 148 | this.SerializeRequest(request, jsonWriter); 149 | } 150 | jsonWriter.WriteEndArray(); 151 | } 152 | else 153 | { 154 | this.SerializeRequest(requests.Single(), jsonWriter); 155 | } 156 | } 157 | return textWriter.ToString(); 158 | 159 | } 160 | 161 | private void SerializeRequest(RpcRequest request, JsonTextWriter jsonWriter) 162 | { 163 | jsonWriter.WriteStartObject(); 164 | jsonWriter.WritePropertyName(JsonRpcContants.IdPropertyName); 165 | jsonWriter.WriteValue(request.Id.Value); 166 | jsonWriter.WritePropertyName(JsonRpcContants.VersionPropertyName); 167 | jsonWriter.WriteValue("2.0"); 168 | jsonWriter.WritePropertyName(JsonRpcContants.MethodPropertyName); 169 | jsonWriter.WriteValue(request.Method); 170 | jsonWriter.WritePropertyName(JsonRpcContants.ParamsPropertyName); 171 | if (!request.Parameters.HasValue) 172 | { 173 | //empty arrray 174 | jsonWriter.WriteStartArray(); 175 | jsonWriter.WriteEndArray(); 176 | } 177 | else 178 | { 179 | switch (request.Parameters.Type) 180 | { 181 | case RpcParametersType.Array: 182 | jsonWriter.WriteStartArray(); 183 | foreach (object value in request.Parameters.ArrayValue) 184 | { 185 | this.SerializeValue(value, jsonWriter); 186 | } 187 | jsonWriter.WriteEndArray(); 188 | break; 189 | case RpcParametersType.Dictionary: 190 | jsonWriter.WriteStartObject(); 191 | foreach (KeyValuePair value in request.Parameters.DictionaryValue) 192 | { 193 | jsonWriter.WritePropertyName(value.Key); 194 | this.SerializeValue(value.Value, jsonWriter); 195 | } 196 | jsonWriter.WriteEndObject(); 197 | break; 198 | } 199 | } 200 | jsonWriter.WriteEndObject(); 201 | } 202 | 203 | 204 | private void SerializeValue(object value, JsonTextWriter jsonWriter) 205 | { 206 | if (value != null) 207 | { 208 | string valueJson; 209 | if (this.jsonSerializerSettings == null) 210 | { 211 | valueJson = JsonConvert.SerializeObject(value); 212 | } 213 | else 214 | { 215 | valueJson = JsonConvert.SerializeObject(value, this.jsonSerializerSettings); 216 | } 217 | jsonWriter.WriteRawValue(valueJson); 218 | } 219 | else 220 | { 221 | jsonWriter.WriteNull(); 222 | } 223 | } 224 | 225 | } 226 | } 227 | 228 | --------------------------------------------------------------------------------