public void Intercept(IInvocation invocation) { if (invocation.Method.ReflectedType == null) throw new Exception("Unknown service type"); var model = new InvocationApiModel { ServiceName = invocation.Method.ReflectedType.Name, MethodName = invocation.Method.Name, Parameters = invocation.Arguments }; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:5000/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsJsonAsync("invokeMethod", model) .ConfigureAwait(false) .GetAwaiter() .GetResult(); if (!response.IsSuccessStatusCode) return; string result = response.Content.ReadAsStringAsync() .ConfigureAwait(false) .GetAwaiter() .GetResult(); object returnValue = JsonConvert.DeserializeObject(result, invocation.Method.ReturnType); invocation.ReturnValue = returnValue; } }
public object Services([FromBody] InvocationApiModel model) { IContractInterface service = _services.FirstOrDefault(s => s.GetType().GetInterfaces().Any(i => i.Name == model.ServiceName)); if (service == null) { throw new Exception($"Service {model.ServiceName} could not be found"); } MethodInfo methodInfo = service.GetType().GetMethods().First(m => m.Name == model.MethodName); if (methodInfo == null) { throw new Exception($"Method {model.MethodName} not found in service {model.ServiceName}"); } var methodParameters = methodInfo.GetParameters(); if (methodParameters.Length == 0) { methodInfo.Invoke(service, null); } if (methodParameters.Length != model.Parameters.Length) { throw new Exception($"Wrong number of parameters for method {model.ServiceName}.{model.MethodName}"); } var parameters = new List <object>(); for (int i = 0; i < methodParameters.Length; i++) { object value = Convert.ChangeType(model.Parameters[i], methodParameters[i].ParameterType); parameters.Add(value); } return(methodInfo.Invoke(service, parameters.ToArray())); }
public void Intercept(IInvocation invocation) { if (invocation.Method.ReflectedType == null) { throw new Exception("Unknown service type"); } var model = new InvocationApiModel { ServiceName = invocation.Method.ReflectedType.Name, MethodName = invocation.Method.Name, Parameters = invocation.Arguments }; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:5000/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsJsonAsync("invokeMethod", model) .ConfigureAwait(false) .GetAwaiter() .GetResult(); if (!response.IsSuccessStatusCode) { return; } string result = response.Content.ReadAsStringAsync() .ConfigureAwait(false) .GetAwaiter() .GetResult(); object returnValue = JsonConvert.DeserializeObject(result, invocation.Method.ReturnType); invocation.ReturnValue = returnValue; } }