|
| 1 | +using JsonAutoService.ResourceHandlers; |
| 2 | +using Microsoft.AspNetCore.Mvc; |
| 3 | +using Microsoft.AspNetCore.Mvc.ApiExplorer; |
| 4 | +using Newtonsoft.Json; |
| 5 | +using Swashbuckle.AspNetCore.SwaggerGen; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Reflection; |
| 9 | +using System.Text; |
| 10 | + |
| 11 | +namespace JsonAutoService.Swashbuckle |
| 12 | +{ |
| 13 | + class RelatableOperationId |
| 14 | + { |
| 15 | + [JsonProperty("resource_handler")] |
| 16 | + public string ResourceHandler { get; set; } |
| 17 | + |
| 18 | + [JsonProperty("procedure_name")] |
| 19 | + public string Procedure { get; set; } |
| 20 | + |
| 21 | + [JsonProperty("method_name")] |
| 22 | + public string Method { get; set; } |
| 23 | + |
| 24 | + [JsonProperty("http_method")] |
| 25 | + public string HttpMethod { get; set; } |
| 26 | + |
| 27 | + [JsonProperty("relative_path")] |
| 28 | + public string RelativePath { get; set; } |
| 29 | + |
| 30 | + public static Func<ApiDescription, string> Create() |
| 31 | + { |
| 32 | + return apiDesc => |
| 33 | + { |
| 34 | + var endpointMetadata = apiDesc.ActionDescriptor.EndpointMetadata; |
| 35 | + |
| 36 | + foreach (object eMetadata in endpointMetadata) |
| 37 | + { |
| 38 | + var result = Utility.TryCast<TypeFilterAttribute>(eMetadata, out TypeFilterAttribute typeFilterAttribute); |
| 39 | + |
| 40 | + if (result) |
| 41 | + { |
| 42 | + if (typeFilterAttribute.ImplementationType.Name == nameof(JsonResourceResultsHandler) || |
| 43 | + typeFilterAttribute.ImplementationType.Name == nameof(JsonResourceContextHandler)) |
| 44 | + { |
| 45 | + var relOperationId = new RelatableOperationId |
| 46 | + { |
| 47 | + ResourceHandler = typeFilterAttribute.ImplementationType.Name, |
| 48 | + Method = apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null, |
| 49 | + Procedure = typeFilterAttribute.Arguments[0].ToString(), |
| 50 | + HttpMethod = apiDesc.HttpMethod, |
| 51 | + RelativePath = apiDesc.RelativePath |
| 52 | + }; |
| 53 | + |
| 54 | + var json = JsonConvert.SerializeObject(relOperationId).ToString(); |
| 55 | + var base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); |
| 56 | + return base64String; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + return null; |
| 61 | + }; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + internal static class Utility |
| 66 | + { |
| 67 | + public static bool TryCast<T>(this object obj, out T result) |
| 68 | + { |
| 69 | + if (obj is T) |
| 70 | + { |
| 71 | + result = (T)obj; |
| 72 | + return true; |
| 73 | + } |
| 74 | + |
| 75 | + result = default(T); |
| 76 | + return false; |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments