public override Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { IServiceProvider serviceProvider = context.HttpContext.RequestServices; MessagePackOptions options = serviceProvider.GetService(typeof(MessagePackOptions)) as MessagePackOptions; MessagePack.IFormatterResolver resolver = options?.Resolver; if (resolver == null) { return(InputFormatterResult.FailureAsync()); } Type actionModelType = context.ModelType; var serializerType = typeof(MessagePackSerializer); var deserializeMethod = serializerType.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(Stream), typeof(IFormatterResolver) }, null); deserializeMethod = deserializeMethod?.MakeGenericMethod(actionModelType); var streamParameter = Expression.Parameter(typeof(Stream), "stream"); var formatterResolver = Expression.Parameter(typeof(IFormatterResolver), "resolver"); var deserializationExpression = Expression.Call(deserializeMethod, streamParameter, formatterResolver); var lambda = Expression.Lambda <DeserializeMethod>(deserializationExpression, new ParameterExpression[] { streamParameter, formatterResolver }).Compile(); var request = context.HttpContext.Request; object instance = lambda(request.Body, resolver); return(InputFormatterResult.SuccessAsync(instance)); }
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { IServiceProvider serviceProvider = context.HttpContext.RequestServices; MessagePackOptions options = serviceProvider.GetService(typeof(MessagePackOptions)) as MessagePackOptions; MessagePack.IFormatterResolver resolver = options?.Resolver; var response = context.HttpContext.Response; byte[] responseBytes = MessagePackSerializer.Serialize(context.Object, resolver); return(response.Body.WriteAsync(responseBytes, 0, responseBytes.Count())); }