├── logo.png ├── src ├── AutomaticApi.Abstraction │ ├── IAutomaticApi.cs │ ├── AutomaticApi.Abstraction.csproj │ └── Attributes │ │ └── SupressMethodAttribute.cs └── AutomaticApi │ ├── AutomaticApi.csproj │ ├── Dynamic │ ├── AutomaticApiHttpMethodAttribute.cs │ ├── AutomaticApiConvention.cs │ ├── AutomaticApiDescriptor.cs │ └── DynamicControllerBuilder.cs │ ├── ServiceCollectionExtensions.cs │ └── AutomaticApiOptions.cs ├── examples └── TestApi │ ├── Entities │ ├── Class.cs │ ├── Student.cs │ └── Teacher.cs │ ├── appsettings.Development.json │ ├── appsettings.json │ ├── Api │ ├── IDemoAService.cs │ ├── ITeacherService.cs │ ├── IDemoBService.cs │ └── IGeneralService.cs │ ├── Services │ ├── TeacherService.cs │ ├── TestService.cs │ └── GenericService.cs │ ├── Properties │ └── launchSettings.json │ ├── BaseController.cs │ ├── Program.cs │ ├── TestApi.csproj │ └── Startup.cs ├── Directory.Build.props ├── LICENSE ├── AutomaticApi.sln ├── README.md └── .gitignore /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/csc414/AutomaticApi/HEAD/logo.png -------------------------------------------------------------------------------- /src/AutomaticApi.Abstraction/IAutomaticApi.cs: -------------------------------------------------------------------------------- 1 | namespace AutomaticApi 2 | { 3 | public interface IAutomaticApi { } 4 | } 5 | -------------------------------------------------------------------------------- /examples/TestApi/Entities/Class.cs: -------------------------------------------------------------------------------- 1 | namespace TestApi.Entities 2 | { 3 | public class Class 4 | { 5 | public string Name { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /examples/TestApi/Entities/Student.cs: -------------------------------------------------------------------------------- 1 | namespace TestApi.Entities 2 | { 3 | public class Student 4 | { 5 | public string Name { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /examples/TestApi/Entities/Teacher.cs: -------------------------------------------------------------------------------- 1 | namespace TestApi.Entities 2 | { 3 | public class Teacher 4 | { 5 | public string Name { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /examples/TestApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /examples/TestApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /src/AutomaticApi.Abstraction/AutomaticApi.Abstraction.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 1.0.1 6 | 7 | 8 | -------------------------------------------------------------------------------- /examples/TestApi/Api/IDemoAService.cs: -------------------------------------------------------------------------------- 1 | using AutomaticApi; 2 | 3 | namespace TestApi.Api 4 | { 5 | public interface IDemoAService : IAutomaticApi 6 | { 7 | /// 8 | /// DemoA 接口 9 | /// 10 | /// 11 | string Get(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/TestApi/Api/ITeacherService.cs: -------------------------------------------------------------------------------- 1 | using AutomaticApi; 2 | using TestApi.Entities; 3 | 4 | namespace TestApi.Api 5 | { 6 | [SupressMethod("InsertAsync", "UpdateAsync")] 7 | public interface ITeacherService : IGeneralService 8 | { 9 | [SupressMethod] 10 | Task TeachAsync(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /examples/TestApi/Services/TeacherService.cs: -------------------------------------------------------------------------------- 1 | using TestApi.Api; 2 | using TestApi.Entities; 3 | 4 | namespace TestApi.Services 5 | { 6 | public class TeacherService : GenericService, ITeacherService 7 | { 8 | public Task TeachAsync() 9 | { 10 | return Task.FromResult(true); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/TestApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "TestApi": { 4 | "commandName": "Project", 5 | "dotnetRunMessages": true, 6 | "launchBrowser": true, 7 | "launchUrl": "swagger", 8 | "applicationUrl": "https://localhost:5000;", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /examples/TestApi/Api/IDemoBService.cs: -------------------------------------------------------------------------------- 1 | using AutomaticApi; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace TestApi.Api 5 | { 6 | public interface IDemoBService : IAutomaticApi 7 | { 8 | /// 9 | /// DemoB 接口 10 | /// 11 | /// 12 | /// 13 | Task FetchAsync(Guid id); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /examples/TestApi/Api/IGeneralService.cs: -------------------------------------------------------------------------------- 1 | using AutomaticApi; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace TestApi.Api 5 | { 6 | public interface IGeneralService : IAutomaticApi 7 | { 8 | Task GetAsync(); 9 | 10 | Task InsertAsync(T model); 11 | 12 | Task UpdateAsync(Guid id, T model); 13 | 14 | Task DeleteAsync(Guid id); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /examples/TestApi/BaseController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.Filters; 3 | 4 | namespace TestApi 5 | { 6 | public class BaseController : Controller 7 | { 8 | public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 9 | { 10 | return base.OnActionExecutionAsync(context, next); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/TestApi/Program.cs: -------------------------------------------------------------------------------- 1 | namespace TestApi 2 | { 3 | public class Program 4 | { 5 | public static void Main(string[] args) 6 | { 7 | Host.CreateDefaultBuilder(args) 8 | .ConfigureWebHostDefaults(webBuilder => 9 | { 10 | webBuilder.UseStartup(); 11 | }) 12 | .Build() 13 | .Run(); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/AutomaticApi/AutomaticApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1;net5.0;net6.0 5 | 1.0.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/AutomaticApi/Dynamic/AutomaticApiHttpMethodAttribute.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Routing; 2 | using System; 3 | 4 | namespace AutomaticApi.Dynamic 5 | { 6 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] 7 | public class AutomaticApiHttpMethodAttribute : HttpMethodAttribute 8 | { 9 | public AutomaticApiHttpMethodAttribute(string httpMethod) : base(new[] { httpMethod }) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/TestApi/Services/TestService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Filters; 2 | using TestApi.Api; 3 | 4 | namespace TestApi.Services 5 | { 6 | public class TestService : IDemoAService, IDemoBService 7 | { 8 | public string Get() 9 | { 10 | return "Hello AutomaticApi"; 11 | } 12 | 13 | public Task FetchAsync(Guid id) 14 | { 15 | return Task.FromResult($"Hello AutomaticApi {id}"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /examples/TestApi/TestApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | true 7 | $(NoWarn);1591 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /examples/TestApi/Services/GenericService.cs: -------------------------------------------------------------------------------- 1 | using TestApi.Api; 2 | 3 | namespace TestApi.Services 4 | { 5 | public class GenericService : IGeneralService where T : new() 6 | { 7 | public Task DeleteAsync(Guid id) 8 | { 9 | return Task.FromResult(true); 10 | } 11 | 12 | public Task GetAsync() 13 | { 14 | return Task.FromResult(new T()); 15 | } 16 | 17 | public Task InsertAsync(T model) 18 | { 19 | return Task.FromResult(true); 20 | } 21 | 22 | public Task UpdateAsync(Guid id, T model) 23 | { 24 | return Task.FromResult(true); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/AutomaticApi.Abstraction/Attributes/SupressMethodAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace AutomaticApi 5 | { 6 | /// 7 | /// Suppress method 8 | /// 9 | [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 10 | public class SupressMethodAttribute : Attribute 11 | { 12 | public SupressMethodAttribute() 13 | { 14 | } 15 | 16 | public SupressMethodAttribute(params string[] methodNames) 17 | { 18 | MethodNames = new HashSet(methodNames); 19 | } 20 | 21 | public HashSet MethodNames { get; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | cxc 4 | AutomaticApi can automatically generate APIs based on services, just define a rest api interface. 5 | Apache-2.0 6 | logo.png 7 | git 8 | https://github.com/csc414/AutomaticApi 9 | https://github.com/csc414/AutomaticApi 10 | MIT 11 | true 12 | 10.0 13 | 14 | 15 | 16 | 17 | True 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 cuixiaochuan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/AutomaticApi/Dynamic/AutomaticApiConvention.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.ApplicationModels; 2 | using System.Linq; 3 | using System.Reflection; 4 | 5 | namespace AutomaticApi.Dynamic 6 | { 7 | public class AutomaticApiConvention : IApplicationModelConvention 8 | { 9 | private readonly FieldInfo _actionMethodField = typeof(ActionModel).GetTypeInfo().DeclaredFields.First(o => o.Name == "k__BackingField"); 10 | 11 | public void Apply(ApplicationModel application) 12 | { 13 | foreach (var controllerModel in application.Controllers) 14 | { 15 | if (typeof(IAutomaticApi).IsAssignableFrom(controllerModel.ControllerType)) 16 | { 17 | var methods = controllerModel.ControllerType.GetInterfaces().SelectMany(o => o.GetTypeInfo().DeclaredMethods).ToDictionary(o => o.ToString()); 18 | foreach (var actionModel in controllerModel.Actions) 19 | _actionMethodField.SetValue(actionModel, methods[actionModel.ActionMethod.ToString()]); 20 | } 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/AutomaticApi/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using AutomaticApi; 2 | using AutomaticApi.Dynamic; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | 7 | namespace Microsoft.Extensions.DependencyInjection 8 | { 9 | public static class ServiceCollectionExtensions 10 | { 11 | private static readonly AutomaticApiOptions _options = new AutomaticApiOptions(); 12 | 13 | internal static DynamicControllerBuilder ControllerBuilder { get; private set; } 14 | 15 | public static IServiceCollection AddAutomaticApi(this IServiceCollection services, Action setupAction) 16 | { 17 | if (ControllerBuilder == null) 18 | { 19 | ControllerBuilder = new DynamicControllerBuilder("AutomaticApi"); 20 | services 21 | .AddControllers(op => op.Conventions.Add(new AutomaticApiConvention())) 22 | .AddApplicationPart(ControllerBuilder.GetAssembly()); 23 | services.PostConfigure(op => ControllerBuilder.AddControllersFromOptions(_options)); 24 | } 25 | 26 | setupAction?.Invoke(_options); 27 | return services; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/AutomaticApi/Dynamic/AutomaticApiDescriptor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | using System.Text; 6 | 7 | namespace AutomaticApi.Dynamic 8 | { 9 | public class AutomaticApiDescriptor 10 | { 11 | public AutomaticApiDescriptor(Type apiServiceType, Type implementationType) 12 | { 13 | ApiServiceType = apiServiceType; 14 | ImplementationType = implementationType; 15 | } 16 | 17 | /// 18 | /// ApiService Type 19 | /// 20 | public Type ApiServiceType { get; } 21 | 22 | /// 23 | /// Implementation Type 24 | /// 25 | public Type ImplementationType { get; } 26 | 27 | /// 28 | /// Controller Name 29 | /// 30 | public string ControllerName { get; set; } 31 | 32 | /// 33 | /// Dynamic Controller parent type, if no definition then use the global options. 34 | /// 35 | public Type ControllerBaseType { get; set; } 36 | 37 | /// 38 | /// Dynamic Controller CustomAttributes 39 | /// 40 | public ICollection>> ControllerAttributes { get; } = new HashSet>>(); 41 | 42 | /// 43 | /// Suppress the ApiService methods 44 | /// 45 | public ICollection SuppressMethods { get; set; } = new HashSet(); 46 | 47 | /// 48 | /// Suppress Global Dynamic Controller CustomAttributes 49 | /// 50 | public bool SuppressGlobalControllerAttributes { get; set; } 51 | 52 | /// 53 | /// Suppress Global DefaultRouteTemplate 54 | /// 55 | public bool SuppressDefaultRouteTemplate { get; set; } 56 | 57 | /// 58 | /// Suppress Global ApiBehavior 59 | /// 60 | public bool SuppressApiBehavior { get; set; } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /examples/TestApi/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.OpenApi.Models; 3 | using System.Reflection; 4 | using TestApi.Api; 5 | using TestApi.Entities; 6 | using TestApi.Services; 7 | 8 | namespace TestApi 9 | { 10 | public class Startup 11 | { 12 | public void ConfigureServices(IServiceCollection services) 13 | { 14 | services.AddSwaggerGen(op => 15 | { 16 | op.SwaggerDoc("1.0", new OpenApiInfo { Title = "TestApi 1.0", Version = "1.0" }); 17 | 18 | foreach (var path in Directory.GetFiles(AppContext.BaseDirectory, "*.xml")) 19 | op.IncludeXmlComments(path, true); 20 | }); 21 | 22 | services.AddAutomaticApi(op => 23 | { 24 | op.AddApi, GenericService>(descriptor => 25 | { 26 | descriptor.ControllerName = nameof(Student); 27 | descriptor.SuppressMethods.Add(typeof(IGeneralService).GetTypeInfo().DeclaredMethods.Last()); 28 | }); 29 | 30 | op.AddApi, GenericService>(descriptor => descriptor.ControllerName = nameof(Class)); 31 | 32 | //op.AddApi(descriptor => descriptor.ControllerBaseType = typeof(BaseController)); //only IDemoAService 33 | 34 | //op.AddApi(); //Generate all api in TestService 35 | 36 | op.AddAssembly(Assembly.GetEntryAssembly()); //Generate all api in Assembly 37 | }); 38 | } 39 | 40 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 41 | { 42 | if (env.IsDevelopment()) 43 | { 44 | app.UseDeveloperExceptionPage(); 45 | 46 | app.UseSwagger(); 47 | app.UseSwaggerUI(op => 48 | { 49 | op.SwaggerEndpoint("/swagger/1.0/swagger.json", "TestApi 1.0"); 50 | }); 51 | } 52 | 53 | app.UseRouting(); 54 | 55 | app.UseEndpoints(endpoints => 56 | { 57 | endpoints.MapControllers(); 58 | }); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /AutomaticApi.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.3.32708.82 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{7A237C19-0A65-4370-AB07-D787B925C2C0}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{7ED559E4-9621-42D6-A0C9-A3980B4AE945}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomaticApi", "src\AutomaticApi\AutomaticApi.csproj", "{4639034B-F59C-4C3B-AF33-B2CEC2A18CF4}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestApi", "examples\TestApi\TestApi.csproj", "{68A37348-7AE1-4230-9439-F8399A1D7D97}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomaticApi.Abstraction", "src\AutomaticApi.Abstraction\AutomaticApi.Abstraction.csproj", "{CDC1B41A-185B-4F72-914B-9D6F30984CAC}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {4639034B-F59C-4C3B-AF33-B2CEC2A18CF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {4639034B-F59C-4C3B-AF33-B2CEC2A18CF4}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {4639034B-F59C-4C3B-AF33-B2CEC2A18CF4}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {4639034B-F59C-4C3B-AF33-B2CEC2A18CF4}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {68A37348-7AE1-4230-9439-F8399A1D7D97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {68A37348-7AE1-4230-9439-F8399A1D7D97}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {68A37348-7AE1-4230-9439-F8399A1D7D97}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {68A37348-7AE1-4230-9439-F8399A1D7D97}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {CDC1B41A-185B-4F72-914B-9D6F30984CAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {CDC1B41A-185B-4F72-914B-9D6F30984CAC}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {CDC1B41A-185B-4F72-914B-9D6F30984CAC}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {CDC1B41A-185B-4F72-914B-9D6F30984CAC}.Release|Any CPU.Build.0 = Release|Any CPU 34 | EndGlobalSection 35 | GlobalSection(SolutionProperties) = preSolution 36 | HideSolutionNode = FALSE 37 | EndGlobalSection 38 | GlobalSection(NestedProjects) = preSolution 39 | {4639034B-F59C-4C3B-AF33-B2CEC2A18CF4} = {7A237C19-0A65-4370-AB07-D787B925C2C0} 40 | {68A37348-7AE1-4230-9439-F8399A1D7D97} = {7ED559E4-9621-42D6-A0C9-A3980B4AE945} 41 | {CDC1B41A-185B-4F72-914B-9D6F30984CAC} = {7A237C19-0A65-4370-AB07-D787B925C2C0} 42 | EndGlobalSection 43 | GlobalSection(ExtensibilityGlobals) = postSolution 44 | SolutionGuid = {E7F36916-0C4C-44C5-A54D-905544D90D2B} 45 | EndGlobalSection 46 | EndGlobal 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AutomaticApi 2 | 3 | AutomaticApi can automatically generate APIs based on services, just define a REST API interface. 4 | 5 | # Installation 6 | 7 | | Package | NuGet Stable | Downloads | 8 | | ------- | ------------ | --------- | 9 | | [AutomaticApi](https://www.nuget.org/packages/AutomaticApi/) | [![AutomaticApi](https://img.shields.io/nuget/v/AutomaticApi.svg)](https://www.nuget.org/packages/AutomaticApi/) | [![AutomaticApi](https://img.shields.io/nuget/dt/AutomaticApi.svg)](https://www.nuget.org/packages/AutomaticApi/) | 10 | | [AutomaticApi.Abstraction](https://www.nuget.org/packages/AutomaticApi.Abstraction/) | [![AutomaticApi.Abstraction](https://img.shields.io/nuget/v/AutomaticApi.Abstraction.svg)](https://www.nuget.org/packages/AutomaticApi.Abstraction/) | [![AutomaticApi.Abstraction](https://img.shields.io/nuget/dt/AutomaticApi.Abstraction.svg)](https://www.nuget.org/packages/AutomaticApi.Abstraction/) | 11 | 12 | # Quick start 13 | 14 | ## 1. Write service code 15 | 16 | ```csharp 17 | public class DemoService 18 | { 19 | public string Get() 20 | { 21 | return "Hello AutomaticApi"; 22 | } 23 | } 24 | ``` 25 | 26 | ## 2. Define the exposed REST API interface we want 27 | 28 | ```csharp 29 | public interface IDemoAService : IAutomaticApi 30 | { 31 | /// 32 | /// DemoA api 33 | /// 34 | /// 35 | string Get(); 36 | } 37 | ``` 38 | 39 | We can also define another REST API interface. 40 | 41 | ```csharp 42 | public interface IDemoBService : IAutomaticApi 43 | { 44 | /// 45 | /// DemoB api 46 | /// 47 | /// 48 | string Get(); 49 | } 50 | ``` 51 | 52 | And implement these interfaces. 53 | 54 | ```csharp 55 | public class DemoService : IDemoAService, IDemoBService 56 | ... 57 | ``` 58 | 59 | ## 3. Configure Services 60 | 61 | ```csharp 62 | public void ConfigureServices(IServiceCollection services) 63 | { 64 | services.AddAutomaticApi(op => 65 | { 66 | op.AddApi(); //only generate IDemoAService 67 | 68 | op.AddApi(); //Generate all api interface in DemoService 69 | 70 | op.AddAssembly(Assembly.GetEntryAssembly()); //Generate all api interface in Assembly 71 | }); 72 | } 73 | ``` 74 | 75 | # What a REST api interface? 76 | 77 | You can totally use it as a controller. 78 | 79 | ```csharp 80 | public interface IDemoService : IAutomaticApi 81 | { 82 | /// 83 | /// DemoB api 84 | /// 85 | /// 86 | [Authorize] 87 | [HttpPost] 88 | [Route("...")] 89 | string UpdateAsync(Guid id, [FromBody] RequestModel model); 90 | } 91 | ``` 92 | 93 | However, `[HttpPost]` `[Route]` usually doesn't need to be defined. AutomaticApi will generates `Route` and `HttpMethod` based on the Method name. 94 | 95 | As we all know, some `[Attrbute]` may can't put it on interface like this. 96 | ``` csharp 97 | [Authorize] 98 | public interface IDemoService : IAutomaticApi 99 | ... 100 | ``` 101 | We can do some customization. 102 | ```csharp 103 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] 104 | public class MyAuthorizeAttribute : AuthorizeAttribute 105 | { 106 | } 107 | ``` 108 | If you think this component can help you, please give me a star. 109 | -------------------------------------------------------------------------------- /src/AutomaticApi/AutomaticApiOptions.cs: -------------------------------------------------------------------------------- 1 | using AutomaticApi.Dynamic; 2 | using Microsoft.AspNetCore.Mvc; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Reflection; 8 | 9 | namespace AutomaticApi 10 | { 11 | public class AutomaticApiOptions 12 | { 13 | internal AutomaticApiOptions() 14 | { 15 | HttpMethodVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase) 16 | { 17 | ["Get"] = "GET", 18 | ["Find"] = "GET", 19 | ["Fetch"] = "GET", 20 | ["Query"] = "GET", 21 | 22 | ["Post"] = "POST", 23 | ["Add"] = "POST", 24 | ["Create"] = "POST", 25 | ["Insert"] = "POST", 26 | 27 | ["Put"] = "PUT", 28 | ["Update"] = "PUT", 29 | ["Edit"] = "PUT", 30 | ["Modify"] = "PUT", 31 | 32 | ["Delete"] = "DELETE", 33 | ["Remote"] = "DELETE", 34 | 35 | ["Patch"] = "PATCH" 36 | }; 37 | 38 | AllowedNameSuffixes = new HashSet { "Service", "ApiService", "AutoApiService" }; 39 | } 40 | 41 | private readonly HashSet _allowedDescriptors = new(); 42 | 43 | /// 44 | /// Allowed descriptors. 45 | /// 46 | public IEnumerable AllowedDescriptors => _allowedDescriptors; 47 | 48 | /// 49 | /// The suffixes of api service name. 50 | /// By default, `IDemoService`, `IDemoApiService`, `IDemoAutoApiService` The api name of these services will be `/api/demo`. 51 | /// 52 | public ICollection AllowedNameSuffixes { get; } 53 | 54 | /// 55 | /// The verb at the start of the method name, that be used in HttpMethod. 56 | /// 57 | public Dictionary HttpMethodVerbs { get; } 58 | 59 | /// 60 | /// Use Api Behavior, Add to Dynamic Controller. 61 | /// The default value is `true`. 62 | /// 63 | public bool UseApiBehavior { get; set; } = true; 64 | 65 | /// 66 | /// Default RouteTemplate, Add to Dynamic Controller. 67 | /// The default value is `api/[controller]`. 68 | /// 69 | public string DefaultRouteTemplate { get; set; } = "api/[controller]"; 70 | 71 | /// 72 | /// Dynamic Controller CustomAttributes 73 | /// 74 | public ICollection>> ControllerAttributes { get; } = new HashSet>>(); 75 | 76 | /// 77 | /// Dynamic Controller parent type. 78 | /// The default value is 79 | /// 80 | public Type ControllerBaseType { get; private set; } = typeof(ControllerBase); 81 | 82 | /// 83 | /// Specify the Dynamic Controller parent type. 84 | /// 85 | /// 86 | public void UseControllerBaseType() where TController : ControllerBase 87 | { 88 | ControllerBaseType = typeof(TController); 89 | } 90 | 91 | /// 92 | /// Add Assembly. 93 | /// Generate the Assembly's own Automatic Api. 94 | /// 95 | /// 96 | /// 97 | public AutomaticApiOptions AddAssembly(Assembly assembly, Func predicate = null) 98 | { 99 | predicate ??= _ => true; 100 | var types = assembly.DefinedTypes.Where(o => o.IsClass && !o.IsAbstract && !o.IsGenericType && typeof(IAutomaticApi).IsAssignableFrom(o)).ToArray(); 101 | foreach (var t in types) 102 | AddApi(t, predicate); 103 | return this; 104 | } 105 | 106 | /// 107 | /// Add Implementation Type. 108 | /// 109 | /// 110 | /// 111 | /// 112 | public AutomaticApiOptions AddApi(Func predicate = null) where TImplementation : class, IAutomaticApi 113 | { 114 | AddApi(typeof(TImplementation).GetTypeInfo(), predicate); 115 | return this; 116 | } 117 | 118 | void AddApi(TypeInfo implementationType, Func predicate = null) 119 | { 120 | predicate ??= _ => true; 121 | var definedInterfaces = implementationType.ImplementedInterfaces.Except 122 | (implementationType.ImplementedInterfaces.SelectMany(t => t.GetInterfaces())) 123 | .Where(o => typeof(IAutomaticApi).IsAssignableFrom(o)).ToArray(); 124 | foreach (var type in definedInterfaces) 125 | { 126 | var descriptor = new AutomaticApiDescriptor(type, implementationType); 127 | if (predicate(descriptor)) 128 | { 129 | Check(descriptor); 130 | _allowedDescriptors.Add(descriptor); 131 | } 132 | } 133 | } 134 | 135 | /// 136 | /// Add ApiService Type and Implementation Type. 137 | /// 138 | /// 139 | /// 140 | /// 141 | /// 142 | /// 143 | public AutomaticApiOptions AddApi(Action configure = null) where TApiService : IAutomaticApi where TImplementation : class, TApiService 144 | { 145 | var t = typeof(TApiService); 146 | if (!t.IsInterface) 147 | throw new ArgumentException($"{nameof(TApiService)} must be a Interface based on IAutomaticApi"); 148 | var descriptor = new AutomaticApiDescriptor(t, typeof(TImplementation)); 149 | configure?.Invoke(descriptor); 150 | Check(descriptor); 151 | _allowedDescriptors.Add(descriptor); 152 | return this; 153 | } 154 | 155 | void Check(AutomaticApiDescriptor descriptor) 156 | { 157 | if (descriptor.ControllerBaseType != null && !typeof(ControllerBase).IsAssignableFrom(descriptor.ControllerBaseType)) 158 | throw new ArgumentException($"{nameof(descriptor.ControllerBaseType)} must based on ControllerBase"); 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /src/AutomaticApi/Dynamic/DynamicControllerBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.Infrastructure; 3 | using Microsoft.AspNetCore.Mvc.Routing; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System; 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | using System.Collections.ObjectModel; 9 | using System.ComponentModel; 10 | using System.Linq; 11 | using System.Linq.Expressions; 12 | using System.Reflection; 13 | using System.Reflection.Emit; 14 | using System.Text.RegularExpressions; 15 | 16 | namespace AutomaticApi.Dynamic 17 | { 18 | internal sealed class DynamicControllerBuilder 19 | { 20 | private readonly MethodInfo _getServiceOrCreateInstance = typeof(ActivatorUtilities).GetTypeInfo().DeclaredMethods.First(o => o.Name.Equals("GetServiceOrCreateInstance")); 21 | 22 | private readonly AssemblyBuilder _ab; 23 | 24 | private readonly ModuleBuilder _mb; 25 | 26 | private AutomaticApiOptions _options; 27 | 28 | private Regex _controllerNameRegex; 29 | 30 | private Regex _nameRegex; 31 | 32 | private Regex _routeRegex; 33 | 34 | public DynamicControllerBuilder(string assemblyName) 35 | { 36 | AssemblyName name = new AssemblyName(assemblyName); 37 | _ab = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); 38 | _mb = _ab.DefineDynamicModule(name.Name); 39 | } 40 | 41 | private void AddController(AutomaticApiDescriptor descriptor) 42 | { 43 | var definedType = descriptor.ApiServiceType.GetTypeInfo(); 44 | var implementationType = descriptor.ImplementationType.GetTypeInfo(); 45 | var controllerName = descriptor.ControllerName ?? GetControllerName(definedType.Name); 46 | 47 | if (definedType.Namespace != null) 48 | controllerName = $"{definedType.Namespace}.{controllerName}"; 49 | 50 | if (_mb.GetType(controllerName) != null) 51 | return; 52 | 53 | var controllerBuilder = _mb.DefineType(controllerName, TypeAttributes.Public, descriptor.ControllerBaseType ?? _options.ControllerBaseType, new[] { definedType }); 54 | var typeAttributes = definedType.GetInterfaces().SelectMany(o => o.GetCustomAttributes()) 55 | .Concat(definedType.GetCustomAttributes()) 56 | .Concat(descriptor.ControllerAttributes.Select(o => o.Compile().Invoke())) 57 | .ToArray(); 58 | var typeAttributeDatas = definedType.GetInterfaces().SelectMany(o => o.GetCustomAttributesData()).Concat(definedType.GetCustomAttributesData()).ToArray(); 59 | foreach (var attrData in typeAttributeDatas) 60 | { 61 | controllerBuilder.SetCustomAttribute(CreateAttribute(attrData)); 62 | } 63 | 64 | if(!descriptor.SuppressGlobalControllerAttributes) 65 | { 66 | typeAttributes = typeAttributes.Concat(_options.ControllerAttributes.Select(o => o.Compile().Invoke())).ToArray(); 67 | 68 | foreach (var item in _options.ControllerAttributes) 69 | { 70 | var attr = CreateAttribute(item); 71 | if(attr != null) 72 | controllerBuilder.SetCustomAttribute(attr); 73 | } 74 | } 75 | 76 | foreach (var item in descriptor.ControllerAttributes) 77 | { 78 | var attr = CreateAttribute(item); 79 | if (attr != null) 80 | controllerBuilder.SetCustomAttribute(attr); 81 | } 82 | 83 | if (!descriptor.SuppressDefaultRouteTemplate && !string.IsNullOrWhiteSpace(_options.DefaultRouteTemplate) && !typeAttributes.Any(o => o is IRouteTemplateProvider p && p.Template != null)) 84 | { 85 | controllerBuilder.SetCustomAttribute(CreateAttribute(_options.DefaultRouteTemplate)); 86 | } 87 | 88 | if (!descriptor.SuppressApiBehavior && _options.UseApiBehavior && !typeAttributes.Any(o => o is IApiBehaviorMetadata)) 89 | { 90 | controllerBuilder.SetCustomAttribute(CreateAttribute()); 91 | } 92 | 93 | var serviceField = controllerBuilder.DefineField("_service", definedType, FieldAttributes.Private); 94 | 95 | var ctorBuilder = controllerBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IServiceProvider) }); 96 | var ctorIL = ctorBuilder.GetILGenerator(); 97 | ctorIL.Emit(OpCodes.Ldarg_0); 98 | ctorIL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); 99 | ctorIL.Emit(OpCodes.Ldarg_0); 100 | ctorIL.Emit(OpCodes.Ldarg_1); 101 | ctorIL.Emit(OpCodes.Call, _getServiceOrCreateInstance.MakeGenericMethod(implementationType)); 102 | ctorIL.Emit(OpCodes.Stfld, serviceField); 103 | ctorIL.Emit(OpCodes.Ret); 104 | 105 | var methods = definedType.GetTypeInfo().DeclaredMethods.Concat(definedType.GetInterfaces().SelectMany(o => o.GetTypeInfo().DeclaredMethods)).ToArray(); 106 | var supressMethods = new HashSet(); 107 | var supressMethodAttr = definedType.GetCustomAttribute(); 108 | if (supressMethodAttr != null) 109 | supressMethods = methods.Where(o => supressMethodAttr.MethodNames.Contains(o.Name)).ToHashSet(); 110 | 111 | foreach (var method in methods) 112 | { 113 | var parameters = method.GetParameters(); 114 | var methodBuilder = controllerBuilder.DefineMethod(method.Name, MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, method.ReturnType, parameters.Select(o => o.ParameterType).ToArray()); 115 | 116 | foreach (var parameter in parameters) 117 | { 118 | var parameterBuilder = methodBuilder.DefineParameter(parameter.Position + 1, parameter.Attributes, parameter.Name); 119 | var parameterAttrDatas = parameter.GetCustomAttributesData(); 120 | foreach (var attr in parameterAttrDatas) 121 | parameterBuilder.SetCustomAttribute(CreateAttribute(attr)); 122 | } 123 | 124 | var attrDatas = method.GetCustomAttributesData(); 125 | foreach (var attr in attrDatas) 126 | methodBuilder.SetCustomAttribute(CreateAttribute(attr)); 127 | 128 | if ((descriptor.SuppressMethods.Contains(method) || supressMethods.Contains(method) || method.GetCustomAttribute() != null) && method.GetCustomAttribute() == null) 129 | methodBuilder.SetCustomAttribute(CreateAttribute()); 130 | 131 | var methodIL = methodBuilder.GetILGenerator(); 132 | methodIL.Emit(OpCodes.Ldarg_0); 133 | methodIL.Emit(OpCodes.Ldfld, serviceField); 134 | foreach (var parameter in parameters) 135 | methodIL.Emit(OpCodes.Ldarg, parameter.Position + 1); 136 | methodIL.Emit(OpCodes.Callvirt, method); 137 | methodIL.Emit(OpCodes.Ret); 138 | 139 | #region Routing 140 | var methodAttrbutes = method.GetCustomAttributes(); 141 | bool hasRoute = methodAttrbutes.Any(o => o is IRouteTemplateProvider p && p.Template != null); 142 | bool hasHttpMethod = methodAttrbutes.Any(o => o is IActionHttpMethodProvider); 143 | var match = _nameRegex.Match(method.Name); 144 | var httpMethod = "POST"; 145 | if (match.Success) 146 | { 147 | if (match.Groups[1].Success) 148 | _options.HttpMethodVerbs.TryGetValue(match.Groups[1].Value, out httpMethod); 149 | 150 | if (!hasRoute) 151 | { 152 | if (match.Groups[2].Success) 153 | { 154 | var matchs = _routeRegex.Matches(match.Groups[2].Value); 155 | var route = default(string); 156 | if (matchs.Count > 0) 157 | route = string.Join("_", matchs.Cast().Select(o => o.Value)); 158 | 159 | if (parameters.Any(o => o.Name.Equals("id", StringComparison.Ordinal))) 160 | { 161 | if (route == null) 162 | route = "{id}"; 163 | else 164 | route = $"{{id}}/{route}"; 165 | } 166 | 167 | if (route != null) 168 | { 169 | methodBuilder.SetCustomAttribute(CreateAttribute(route)); 170 | hasRoute = true; 171 | } 172 | } 173 | } 174 | } 175 | 176 | if (!hasHttpMethod) 177 | methodBuilder.SetCustomAttribute(CreateAttribute(typeof(AutomaticApiHttpMethodAttribute), httpMethod)); 178 | 179 | #endregion 180 | } 181 | 182 | controllerBuilder.CreateType(); 183 | } 184 | 185 | public void AddControllersFromOptions(AutomaticApiOptions options) 186 | { 187 | _options = options; 188 | 189 | _controllerNameRegex = new Regex($"^(?:I)(.+?)(?:{string.Join("|", options.AllowedNameSuffixes)})?$", RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.Compiled); 190 | 191 | _nameRegex = new Regex($"^({string.Join("|", options.HttpMethodVerbs.Keys)})?(.*?)(?:Async)?$", RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.Compiled); 192 | 193 | _routeRegex = new Regex("[A-Z]{0,1}[a-z0-9]+", RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.Compiled); 194 | 195 | foreach (var descriptor in _options.AllowedDescriptors) 196 | AddController(descriptor); 197 | } 198 | 199 | public Assembly GetAssembly() => _ab; 200 | 201 | CustomAttributeBuilder CreateAttribute(params object[] args) where T : Attribute 202 | { 203 | return CreateAttribute(typeof(T), args); 204 | } 205 | 206 | CustomAttributeBuilder CreateAttribute(Type type, params object[] args) 207 | { 208 | ConstructorInfo constructorInfo = type.GetConstructor(args.Select(o => o.GetType()).ToArray()); 209 | return new CustomAttributeBuilder(constructorInfo, args); 210 | } 211 | 212 | CustomAttributeBuilder CreateAttribute(CustomAttributeData attrData) 213 | { 214 | var fields = attrData.NamedArguments.Where(o => o.IsField); 215 | var properties = attrData.NamedArguments.Where(o => !o.IsField); 216 | return new CustomAttributeBuilder(attrData.Constructor, attrData.ConstructorArguments.Select(o => { 217 | if(o.Value is ReadOnlyCollection args) 218 | return args.Select(o => o.Value).ToArray(); 219 | 220 | return o.Value; 221 | }).ToArray(), properties.Select(o => (PropertyInfo)o.MemberInfo).ToArray(), properties.Select(o => o.TypedValue.Value).ToArray(), fields.Select(o => (FieldInfo)o.MemberInfo).ToArray(), fields.Select(o => o.TypedValue.Value).ToArray()); 222 | } 223 | 224 | CustomAttributeBuilder CreateAttribute(LambdaExpression lambda) 225 | { 226 | if (lambda.Body.NodeType != ExpressionType.New && lambda.Body.NodeType != ExpressionType.MemberInit) 227 | return null; 228 | 229 | var memberInitExp = lambda.Body as MemberInitExpression; 230 | var newExp = memberInitExp?.NewExpression ?? lambda.Body as NewExpression; 231 | var constructorArgs = newExp.Arguments.Select(o => GetValue(o)).ToArray(); 232 | 233 | if (memberInitExp == null) 234 | return new CustomAttributeBuilder(newExp.Constructor, constructorArgs); 235 | 236 | var memberInfos = memberInitExp.Bindings.Where(o => o.Member.MemberType == MemberTypes.Property && o.BindingType == MemberBindingType.Assignment).Select(o => (Property: (PropertyInfo)o.Member, Value: GetValue(((MemberAssignment)o).Expression))).ToArray(); 237 | 238 | return new CustomAttributeBuilder(newExp.Constructor, constructorArgs, memberInfos.Select(o => o.Property).ToArray(), memberInfos.Select(o => o.Value).ToArray()); 239 | } 240 | 241 | object GetValue(Expression expression) 242 | { 243 | if (expression == null) 244 | return null; 245 | 246 | if (expression.NodeType == ExpressionType.Convert) 247 | return GetValue(((UnaryExpression)expression).Operand); 248 | 249 | if (expression.NodeType == ExpressionType.Constant) 250 | return ((ConstantExpression)expression).Value; 251 | 252 | if (expression is MemberExpression memberExpression) 253 | { 254 | var obj = GetValue(memberExpression.Expression); 255 | if (memberExpression.Member is PropertyInfo propertyInfo) 256 | return propertyInfo.GetValue(obj); 257 | 258 | if (memberExpression.Member is FieldInfo fieldInfo) 259 | return fieldInfo.GetValue(obj); 260 | } 261 | 262 | if (expression is MethodCallExpression methodCallExpression) 263 | { 264 | var args = methodCallExpression.Arguments.Select(o => GetValue(o)).ToArray(); 265 | object obj = null; 266 | if (methodCallExpression.Object != null) 267 | obj = GetValue(methodCallExpression.Object); 268 | return methodCallExpression.Method.Invoke(obj, args); 269 | } 270 | 271 | if (expression is NewArrayExpression newArrayExpression) 272 | { 273 | var args = newArrayExpression.Expressions.Select(o => GetValue(o)).ToArray(); 274 | var ary = (object[])Activator.CreateInstance(newArrayExpression.Type, args.Length); 275 | for (int i = 0; i < ary.Length; ++i) 276 | ary[i] = args[i]; 277 | return ary; 278 | } 279 | 280 | if (expression is BinaryExpression binaryExpression) 281 | { 282 | switch (expression.NodeType) 283 | { 284 | case ExpressionType.Coalesce: 285 | { 286 | var value = GetValue(binaryExpression.Left); 287 | if (value == null) 288 | value = GetValue(binaryExpression.Right); 289 | return value; 290 | } 291 | case ExpressionType.ArrayIndex: 292 | { 293 | var array = (Array)GetValue(binaryExpression.Left); 294 | var index = (long)Convert.ChangeType(GetValue(binaryExpression.Right), typeof(long)); 295 | return array.GetValue(index); 296 | } 297 | } 298 | 299 | } 300 | 301 | throw new NotImplementedException($"NodeType:{expression.NodeType}"); 302 | } 303 | 304 | string GetControllerName(string apiName) 305 | { 306 | var match = _controllerNameRegex.Match(apiName); 307 | string controllerName; 308 | if (match.Success) 309 | controllerName = match.Groups[1].Value; 310 | else 311 | controllerName = apiName; 312 | return $"{controllerName}Controller"; 313 | } 314 | } 315 | } 316 | --------------------------------------------------------------------------------