Exemple #1
0
        public Task CallOperationFromContentTypeOfJson(HttpContext httpContext, NetStitchServer server, OperationController operation)
        {
            try
            {
                var    args = new List <object>();
                object obj;
                string body;

                using (var sr = new StreamReader(httpContext.Request.Body, Encoding.UTF8))
                {
                    body = sr.ReadToEnd();
                }
                if (operation.ParameterType == typeof(byte[]) && string.IsNullOrWhiteSpace(body))
                {
                    body = "[]";
                }

                obj = Newtonsoft.Json.JsonConvert.DeserializeObject(body, operation.ParameterType);

                httpContext.Request.Body = new System.IO.MemoryStream();
                if (obj != null)
                {
                    MessagePack.LZ4MessagePackSerializer.NonGeneric.Serialize(operation.ParameterType, httpContext.Request.Body, obj, server.Option.FormatterResolver);
                }

                return(next(httpContext));
            }
            catch (Exception ex)
            {
                httpContext.Response.StatusCode = HttpStatus.InternalServerError;
                var bytes = Encoding.UTF8.GetBytes(ex.ToString());
                httpContext.Response.Body.Write(bytes, 0, bytes.Length);
                return(Task.CompletedTask);
            }
        }
Exemple #2
0
        public Task CallSwagger(HttpContext httpContext, NetStitchServer server)
        {
            const string prefix = "NetStitch.Swagger.SwaggerUI.";

            var path = httpContext.Request.Path.Value.Trim('/');

            if (path == "")
            {
                path = "index.html";
            }
            var filePath = prefix + path.Replace("/", ".");

            if (MediaTypeDictionary.TryGetValue(filePath.Split('.').Last(), out string mediaType))
            {
                if (path.EndsWith(options.JsonName))
                {
                    var builder = new SwaggerBuilder(options, httpContext);
                    var bytes   = builder.BuildSwagger(server);
                    httpContext.Response.ContentType = "application/json";
                    httpContext.Response.StatusCode  = HttpStatus.OK;
                    httpContext.Response.Body.Write(bytes, 0, bytes.Length);
                    return(Task.CompletedTask);
                }

                var myAssembly = typeof(NetStitchSwaggerMiddleware).GetTypeInfo().Assembly;

                using (var stream = myAssembly.GetManifestResourceStream(filePath))
                {
                    if (stream == null)
                    {
                        return(next(httpContext));
                    }
                    httpContext.Response.ContentType = mediaType;
                    httpContext.Response.StatusCode  = HttpStatus.OK;
                    var response = httpContext.Response.Body;
                    stream.CopyTo(response);
                }
            }
            ;

            return(Task.CompletedTask);
        }
        public byte[] BuildSwagger(NetStitchServer server)
        {
            try
            {
                if (options.XmlDocumentPath != null && !File.Exists(options.XmlDocumentPath))
                {
                    return(Encoding.UTF8.GetBytes("Xml doesn't exists at " + options.XmlDocumentPath));
                }

                xDocLookup = (options.XmlDocumentPath != null)
                    ? BuildXmlMemberCommentStructure(options.XmlDocumentPath)
                    : null;

                var doc = new SwaggerDocument();
                doc.info        = options.Info;
                doc.host        = (options.CustomHost != null) ? options.CustomHost(httpContext) : httpContext.Request.Headers["Host"][0];
                doc.basePath    = options.ApiBasePath;
                doc.schemes     = (options.ForceSchemas.Length == 0) ? new[] { httpContext.Request.IsHttps ? "https" : httpContext.Request.Scheme } : options.ForceSchemas;
                doc.paths       = new Dictionary <string, PathItem>();
                doc.definitions = new Dictionary <string, Schema>();

                // tags.
                var xmlServiceName = (options.XmlDocumentPath != null)
                    ? BuildXmlTypeSummary(options.XmlDocumentPath)
                    : null;

                doc.tags = server.OperationMap.Values
                           .Select(x => x.OperationID)
                           .Distinct()
                           .Select(x =>
                {
                    string desc = null;
                    if (xmlServiceName != null)
                    {
                        xmlServiceName.TryGetValue(x, out desc);
                    }
                    return(new Tag()
                    {
                        name = x,
                        description = desc
                    });
                })
                           .ToArray();

                foreach (var item in server.OperationMap.Values)
                {
                    XmlCommentStructure xmlComment = null;
                    if (xDocLookup != null)
                    {
                        xmlComment = xDocLookup[Tuple.Create(item.OperationID, item.MethodInfo.Name)].FirstOrDefault();
                    }

                    var parameters = BuildParameters(doc.definitions, xmlComment, item.MethodInfo);
                    var operation  = new Operation
                    {
                        tags        = new[] { item.InterfaceType.Name },
                        summary     = (xmlComment != null) ? xmlComment.Summary : "",
                        description = (xmlComment != null) ? xmlComment.Remarks : "",
                        parameters  = parameters
                    };

                    doc.paths.Add("/" + item.ToString(), new PathItem {
                        post = operation
                    });
                }

                using (var ms = new MemoryStream())
                    using (var sw = new StreamWriter(ms, new UTF8Encoding(false)))
                    {
                        var serializer = new JsonSerializer()
                        {
                            NullValueHandling = NullValueHandling.Ignore,
                            ContractResolver  = IgnoreEmptyEnumerablesResolver.Instance
                        };
                        serializer.Serialize(sw, doc);

                        //todo gzip encording

                        sw.Flush();
                        return(ms.ToArray());
                    }
            }
            catch (Exception ex)
            {
                return(Encoding.UTF8.GetBytes(ex.ToString()));
            }
        }
Exemple #4
0
        public Task CallOperationFromContentTypeOfFormUrlencoded(HttpContext httpContext, NetStitchServer server, OperationController operation)
        {
            var    args = new List <object>();
            object obj;
            var    typeArgs = new List <Type>();

            try
            {
                foreach (var methodParameter in operation.MethodInfo.GetParameters())
                {
                    typeArgs.Add(methodParameter.ParameterType);

                    if (httpContext.Request.Form.TryGetValue(methodParameter.Name, out var stringValues))
                    {
                        if (methodParameter.ParameterType == typeof(string))
                        {
                            args.Add((string)stringValues);
                        }
                        else if (methodParameter.ParameterType.GetTypeInfo().IsEnum)
                        {
                            args.Add(Enum.Parse(methodParameter.ParameterType, (string)stringValues));
                        }
                        else
                        {
                            var collectionType = GetCollectionType(methodParameter.ParameterType);
                            if (collectionType == null || stringValues.Count == 1)
                            {
                                var values = (string)stringValues;

                                if (methodParameter.ParameterType == typeof(DateTime) ||
                                    methodParameter.ParameterType == typeof(DateTimeOffset) ||
                                    methodParameter.ParameterType == typeof(DateTime?) ||
                                    methodParameter.ParameterType == typeof(DateTimeOffset?))
                                {
                                    values = "\"" + values + "\"";
                                }

                                args.Add(JsonConvert.DeserializeObject(values, methodParameter.ParameterType));
                            }
                            else
                            {
                                string serializeTarget;
                                if (collectionType == typeof(string))
                                {
                                    serializeTarget = $"[{string.Join(", ", stringValues.Select(x => JsonConvert.SerializeObject(x)))}]";
                                }
                                else if (collectionType.GetTypeInfo().IsEnum ||
                                         collectionType == typeof(DateTime) ||
                                         collectionType == typeof(DateTimeOffset) ||
                                         collectionType == typeof(DateTime?) ||
                                         collectionType == typeof(DateTimeOffset?))
                                {
                                    serializeTarget = $"[{string.Join(", ", stringValues.Select(x => "\"" + x + "\""))}]";
                                }
                                else
                                {
                                    serializeTarget = $"[{(string)stringValues}]";
                                }

                                args.Add(JsonConvert.DeserializeObject(serializeTarget, methodParameter.ParameterType));
                            }
                        }
                    }
                    else
                    {
                        if (methodParameter.HasDefaultValue)
                        {
                            args.Add(methodParameter.DefaultValue);
                        }
                        else
                        {
                            args.Add(null);
                        }
                    }
                }
                obj = Activator.CreateInstance(operation.ParameterType, args.ToArray());
                httpContext.Request.Body = new System.IO.MemoryStream();
                if (obj != null)
                {
                    MessagePack.LZ4MessagePackSerializer.NonGeneric.Serialize(operation.ParameterType, httpContext.Request.Body, obj, server.Option.FormatterResolver);
                }
                return(next(httpContext));
            }
            catch (Exception ex)
            {
                httpContext.Response.StatusCode = HttpStatus.InternalServerError;
                var bytes = Encoding.UTF8.GetBytes(ex.ToString());
                httpContext.Response.Body.Write(bytes, 0, bytes.Length);
            }
            return(Task.CompletedTask);
        }