### Install Rezero API Package Source: https://github.com/dotnetnext/rezero/blob/master/README.md Install the Rezero.Api NuGet package to integrate Rezero into your .NET project. ```csharp Rezero.Api ``` -------------------------------- ### SQLite Connection String Example Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/database_manager.html Simple connection string for SQLite databases, primarily requiring the path to the database file. ```sql Sqlite示例: DataSource=xxx.sqlite ``` -------------------------------- ### MySQL Connection String Example Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/database_manager.html Use this format for connecting to a MySQL database. Specify the server, database, UID, and PWD. A port can be added if not using the default. ```sql MySql示例: server=localhost;Database=SqlSugar4xTest;Uid=root;Pwd=haosql; 非默认端口要用port=3306 ``` -------------------------------- ### SQL Server Connection String Example Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/database_manager.html Example connection string for SQL Server. Note the settings for .NET 8 regarding invariant globalization and potential port specification. ```sql SqlServer示例: server=.;uid=sa;pwd=sasa;database=SuperAPI;Encrypt=True;TrustServerCertificate=True .net8需要注意 启动文件csproj文件 ,InvariantGlobalization设置为false 有端口localhost:1433; ``` -------------------------------- ### PostgreSQL Connection String Example Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/database_manager.html Connection string for PostgreSQL. Includes host, port, database, user, and password. If not using the default 'public' schema, specify the search path. ```sql Postgresql 示例: PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres 不是public需要设置架构名searchpath=架构名 ``` -------------------------------- ### Dameng Connection String Example Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/database_manager.html Connection string format for Dameng databases, including server address, port, user ID, password, and schema. ```sql 达梦 示例: Server=153.101.101:5236;User Id=SYSDBA;PWD=123456;SCHEMA=架构;DATABASE=DAMENG ``` -------------------------------- ### Oracle Connection String Examples Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/database_manager.html Two common formats for connecting to Oracle databases. The second format is an alternative if the first fails, often used for specific network configurations. ```sql Oracle: //写法1 Data Source=localhost/orcl;User ID=system;Password=haha //字法2 上面连不上可以试用下面写法 Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=150.158.57.125)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User Id=xx;Password=xx;Pooling='true';Max Pool Size=150 ``` -------------------------------- ### Kingbase Connection String Example Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/database_manager.html Connection string for Kingbase databases. Specify server, port, UID, PWD, and database name. Note that the default mode is Oracle, and adjustments may be needed for other modes. ```sql 人大金仓 示例: Server=127.0.0.1;Port=54321;UID=SYSTEM;PWD=system;database=SQLSUGAR4XTEST1 默认是Oracle模式,如果不是Oracle模式需要看SqlSugar文档改ReZero源码 通过SQL可以查看安装模式 show database_mode; ``` -------------------------------- ### Bind Templates Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Fetches available templates using an Axios GET request. Populates the templates list and sets the initial current template. ```javascript bindTemplates: function () { var th = this; var url = "/PrivateReZeroRoute/100003/GetTemplateListByTypeId?typeId=1"; axios.get(url, jwHeader) .then(response => { th.templates = response.data; th.currentTemplate = th.templates[0]; th.currentTemplateId = th.templates[0].Id; }) .catch(error => { th.error = error.message; }); } ``` -------------------------------- ### Load ReZero Configuration from JSON File Source: https://context7.com/dotnetnext/rezero/llms.txt Loads ReZero configuration from a specified JSON file (defaults to appsettings.json) into SuperAPIOptions. This method supports loading from custom configuration files for multi-environment setups. Ensure custom files are located in the same directory as the executable or DLL. ```csharp // 从默认 appsettings.json 读取 var options = SuperAPIOptions.GetOptions(); // 从自定义配置文件读取(文件需与 EXE/DLL 在同一目录) var options = SuperAPIOptions.GetOptions("rezero.json"); // rezero.json 示例 // { // "ReZero": { // "BasicDatabase": { "DbType": "MySql", "ConnectionString": "server=...;database=mydb;..." }, // "Jwt": { "Enable": true, "Secret": "...", "UserTableName": "sys_user", ... } // } // } builder.Services.AddReZeroServices(api => { var apiObj = SuperAPIOptions.GetOptions("rezero.json"); apiObj!.DependencyInjectionOptions = new DependencyInjectionOptions(Assembly.GetExecutingAssembly()); api.EnableSuperApi(apiObj); }); ``` -------------------------------- ### Vue.js Initialization and Token Handling Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/authorization.html Initializes a Vue instance to manage authorization data, including token retrieval and storage. It sets up methods for submitting tokens, getting tokens via API calls, and fetching user info. ```javascript var vueObj = new Vue({ el: '#apibox', data: { data: null, error: null, txtToken: null, userName: null, password: null, result: null, jwtInfo:null, hashedPasswords: [] }, mounted() { if (jwHeader && jwHeader.headers) { this.txtToken = (jwHeader.headers.Authorization + "") .replace("Bearer null", "Bearer ") .replace("Bearer ", ""); } }, methods: { submitToken: function () { if (!this.txtToken) { tools.alert("token不能为空"); } else { localStorage["@@authorizationLocalStorageName"] = this.txtToken; tools.alert("设置成功"); setTimeout(function () { window.location.href = "/rezero/Authorization.html"; }, 1000); } }, getToken: function () { if (!this.userName || !this.password) { tools.alert("用户名或者密码不能为空"); } else { axios.post("/api/rezero/token?supportCustomDto=true", { userName: this.userName, password: this.password+"" }, jwHeader) .then(response => { this.error = null; this.result = response.data; }) .catch(error => { this.error = error.message; this.data = null; }); } }, MD5: function () { if (this.password) { // No need to hash if password is already hashed var existingHash = this.hashedPasswords.find(entry => entry.password === this.password); if (!existingHash) { var hashedPassword = CryptoJS.MD5(this.password); this.password = hashedPassword; this.hashedPasswords.push({ password: this.password, hashedPassword }); } } }, getUserInfo: function () { axios.get("/api/rezero/getuserinfo", jwHeader) .then(response => { this.error = null; this.jwtInfo = response.data; }) .catch(error => { this.error = error.message; this.data = null; }); } } }); ``` -------------------------------- ### Calling SQL Script Interface via cURL Source: https://context7.com/dotnetnext/rezero/llms.txt Example of how to call the SQL script interface endpoint using cURL, including necessary headers and a JSON payload for parameters. ```bash curl -X POST http://localhost:65000/api/orders/query \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "userId": 1, "status": "paid", "pageNumber": 1, "pageSize": 20 }' ``` -------------------------------- ### AddReZeroServices - Register ReZero Services Source: https://context7.com/dotnetnext/rezero/llms.txt Registers ReZero services including SuperAPI, dependency injection, and JWT into the ASP.NET Core DI container. It supports two overloads: Action for configuration and ReZeroOptions for direct setup. ```APIDOC ## AddReZeroServices ### Description Registers ReZero services (SuperAPI, dependency injection, JWT) into the ASP.NET Core DI container. This is the sole entry point for integrating ReZero. It supports `Action` and `ReZeroOptions` overloads. ### Method Signature ```csharp public static IServiceCollection AddReZeroServices(this IServiceCollection services, Action setupAction) public static IServiceCollection AddReZeroServices(this IServiceCollection services, ReZeroOptions options) ``` ### Usage Example (.NET 6+ Web API) ```csharp // Program.cs using ReZero; using ReZero.SuperAPI; using System.Reflection; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Method 1: Configure via Action (Recommended) builder.Services.AddReZeroServices(api => { // GetOptions() reads database/JWT/Cors configurations from the "ReZero" node in appsettings.json var apiObj = SuperAPIOptions.GetOptions(); // Register business assembly for IOC auto-scan and code interfaces apiObj!.DependencyInjectionOptions = new DependencyInjectionOptions(Assembly.GetExecutingAssembly()); // Enable Super API api.EnableSuperApi(apiObj); }); // Method 2: Configure directly via ReZeroOptions (for pure IOC integration without SuperAPI UI) builder.Services.AddReZeroServices(new ReZeroOptions() { DependencyInjectionOptions = new DependencyInjectionOptions(typeof(Program).Assembly) }); var app = builder.Build(); app.UseAuthorization(); app.MapControllers(); app.Run(); // Access the ReZero management interface at http://localhost:5267/rezero after startup ``` ### Parameters * **services**: The `IServiceCollection` to add services to. * **setupAction**: An `Action` to configure SuperAPI options. * **options**: A `ReZeroOptions` object for direct configuration. ``` -------------------------------- ### Fetch All Tables Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Fetches all tables for a given database ID using an Axios GET request. Handles success by updating the 'allTables' data and errors by updating the 'error' message. ```javascript axios.get(url, jwHeader) .then(response => { this.allTables = response.data; this.error = null; }) .catch(error => { this.error = error.message; }); ``` -------------------------------- ### Export Entities to Excel Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Exports selected entities to an Excel file. It sends a GET request with selected table IDs and the database ID, then handles the blob response to create a downloadable Excel file. ```javascript var th = this; axios.get("/PrivateReZeroRoute/100003/ExportEntities", { params: { tableIds: JSON.stringify(this.selectedItems), DataBaseId: this.databaseId }, responseType: 'blob', headers: jwHeader.headers }) .then(function (response) { // 创建一个 Blob 对象,指向数据的 URL var url = window.URL.createObjectURL(new Blob([response.data])); var link = document.createElement('a'); link.href = url; ``` -------------------------------- ### Get Setting Item Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Fetches a specific setting item's value using an Axios POST request. Updates the component's state with the retrieved value or an error message. ```javascript getSettingItem: function (typeId, childTypeId) { var url = "/PrivateReZeroRoute/100003/GetSetting"; var th = this; axios.post(url, { typeId: typeId, childTypeId: childTypeId }, jwHeader) .then(response => { th.setting.importUnunderline = response.data.BoolValue; this.error = null; }) .catch(error => { this.error = error.message; this.data = null; }); } ``` -------------------------------- ### Initialize Vue Instance for System Configuration Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/sys_config.html Initializes the Vue instance for the system configuration page. It sets up data properties for various configurations and defines methods for fetching and saving settings. ```javascript var vueObj = new Vue({ el: '#apibox', data: { ReZero: { config: { Enable: false } }, setting: { importUnunderline: false }, licenseConfig: {} }, mounted() { //this.getLoginConfig(); this.getSettingItem(1, 1); this.getLicenseConfig(); }, methods: { //getLoginConfig: function () { // axios.get('/PrivateReZeroRoute/100003/getLoginConfig') // .then(response => { // this.ReZero.config.Enable = response.data; // }) // .catch(error => { // console.error(error); // }); //}, //saveLoginConfig: function () { // var url = "/PrivateReZeroRoute/100003/saveLoginConfig"; // axios.post(url, { enable: this.ReZero.config.Enable }, jwHeader) // .then(response => { // tools.alert("登录配置保存成功"); // this.error = null; // }) // .catch(error => { // this.error = error.message; // this.data = null; // }); //}, saveSetting: function () { this.saveSettingItem(1, 1, this.setting.importUnunderline); }, getSettingItem: function (typeId, childTypeId) { var url = "/PrivateReZeroRoute/100003/GetSetting"; axios.post(url, { typeId: typeId, childTypeId: childTypeId }, jwHeader) .then(response => { this.setting.importUnunderline = response.data.BoolValue; this.error = null; }) .catch(error => { this.error = error.message; this.data = null; }); }, saveSettingItem: function (typeId, childTypeId, value) { var url = "/PrivateReZeroRoute/100003/UpdateSetting"; axios.post(url, { typeId: typeId, childTypeId: childTypeId, value: value }, jwHeader) .then(response => { tools.alert("实体管理配置保存成功"); this.error = null; }) .catch(error => { this.error = error.message; this.data = null; }); }, clearInternalCache: function () { axios.get("/PrivateReZeroRoute/100003/ClearAllInternalCache", jwHeader) .then(response => { tools.alert("清除成功"); this.error = null; }) .catch(error => { this.error = error.message; this.data = null; }); }, getLicenseConfig() { axios.post('/PrivateReZeroRoute/100003/GetLicenseConfig', {}, jwHeader) .then(res => { this.licenseConfig = res.data; }); }, saveLicenseConfig() { var th = this; axios.post('/PrivateReZeroRoute/100003/SaveLicenseConfig', { license: this.licenseConfig.License }, jwHeader) .then(() => { tools.alert('保存成功'); window.location.href = window.location.href; } ); } } }); ``` -------------------------------- ### SuperAPIOptions.GetOptions - Load Configuration from JSON Source: https://context7.com/dotnetnext/rezero/llms.txt Loads ReZero configurations from a specified JSON file (defaults to appsettings.json) and constructs a SuperAPIOptions object. It supports loading from custom filenames for multi-environment configuration separation. ```APIDOC ## SuperAPIOptions.GetOptions ### Description Loads the `ReZero` configuration node from a specified JSON file (defaults to `appsettings.json`) or a custom file, and constructs a `SuperAPIOptions` object. This method is useful for loading configurations, especially when managing multiple environments. ### Method Signature ```csharp public static SuperAPIOptions GetOptions(string? fileName = null) ``` ### Usage Examples **1. Load from default `appsettings.json`:** ```csharp var options = SuperAPIOptions.GetOptions(); ``` **2. Load from a custom configuration file (e.g., `rezero.json`):** *The file should be located in the same directory as the EXE/DLL.* ```csharp var options = SuperAPIOptions.GetOptions("rezero.json"); ``` **Example `rezero.json`:** ```json { "ReZero": { "BasicDatabase": { "DbType": "MySql", "ConnectionString": "server=...;database=mydb;..." }, "Jwt": { "Enable": true, "Secret": "...", "UserTableName": "sys_user", ... } } } ``` **Integration Example:** ```csharp // In Program.cs or Startup.cs builder.Services.AddReZeroServices(api => { var apiObj = SuperAPIOptions.GetOptions("rezero.json"); // Load from custom file apiObj!.DependencyInjectionOptions = new DependencyInjectionOptions(Assembly.GetExecutingAssembly()); api.EnableSuperApi(apiObj); }); ``` ### Parameters * **fileName** (optional): The name of the JSON configuration file. If null, `appsettings.json` is used. ``` -------------------------------- ### Fetch License Configuration Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/sys_config.html Fetches the license configuration by sending a POST request to '/PrivateReZeroRoute/100003/GetLicenseConfig'. The response data is assigned to the 'licenseConfig' property. ```javascript getLicenseConfig() { axios.post('/PrivateReZeroRoute/100003/GetLicenseConfig', {}, jwHeader) .then(res => { this.licenseConfig = res.data; }); } ``` -------------------------------- ### Open Settings Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Triggers a click event on the 'btnSetting' element and then calls 'getSettingItem' to retrieve settings. ```javascript openSetting: function () { btnSetting.click(); this.getSettingItem(1, 1); } ``` -------------------------------- ### Clear Internal Cache via API Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/sys_config.html This method clears all internal caches by making a GET request to the '/PrivateReZeroRoute/100003/ClearAllInternalCache' endpoint. It displays an alert upon successful clearing or logs an error. ```javascript clearInternalCache: function () { axios.get("/PrivateReZeroRoute/100003/ClearAllInternalCache", jwHeader) .then(response => { tools.alert("清除成功"); this.error = null; }) .catch(error => { this.error = error.message; this.data = null; }); } ``` -------------------------------- ### Execute SQL and Return Excel Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Executes a SQL query and downloads the result as an Excel file. Uses 'blob' response type and dynamically creates a download link. Includes error handling. ```javascript var editor = ace.edit("divAceEditor"); var sql = editor.getValue("\r\n"); var th = this; axios.get("/PrivateReZeroRoute/100003/ExecuetSqlReturnExcel", { params: { databaseId: this.databaseId, sql: sql }, responseType: 'blob', headers: jwHeader.headers }) .then(function (response) { // 创建一个 Blob 对象,指向数据的 URL var url = window.URL.createObjectURL(new Blob([response.data])); var link = document.createElement('a'); link.href = url; // 设置下载文件的名称,可以根据实际情况调整 var fileName = 'sql.xlsx'; link.setAttribute('download', fileName); // 触发下载 document.body.appendChild(link); link.click(); // 清理资源 window.URL.revokeObjectURL(link.href); document.body.removeChild(link); }) .catch(function (error) { console.error("Error downloading the Excel file:", error); }); ``` -------------------------------- ### Embedding ReZero UI in an Existing System using iframe Source: https://context7.com/dotnetnext/rezero/llms.txt Demonstrates how to embed the ReZero interface management UI into an existing web page using an iframe. The `model=small` parameter hides navigation elements, and the `token` parameter handles JWT authentication. ```html 接口管理

业务系统 - 接口管理模块

``` -------------------------------- ### Initialize Vue Instance for JWT Token Management Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/jwt_token_management.html Sets up the Vue instance with data properties for managing JWT tokens, including token details, user lists, and UI states. It fetches initial data and user lists upon mounting. ```javascript var vueObj = new Vue({ el: '#apibox', data: { data: null, error: null, bizUserErrorMessage: "", title: "添加JWT Token", formData: { Id: 0, UserName: '', Description: '', Expiration: '', Token: '' }, selectedItems: [], users: [], // 添加用户列表 isReadOnly: false // 添加只读状态 }, mounted() { this.fetchData(""); this.fetchUsers(); }, methods: { fetchData: function (append) { var url = "/PrivateReZeroRoute/100003/GetZeroJwtTokenManagementPage" + append; axios.get(url, jwHeader) .then(response => { this.data = response.data; this.error = null; }) .catch(error => { this.error = error.message; this.data = null; }); }, fetchUsers: function () { var url = "/PrivateReZeroRoute/100003/GetBizUsers"; // 获取用户列表的API axios.get(url, jwHeader) .then(response => { if (Array.isArray(response.data)) { this.users = response.data; } else if (response.data.message) { this.bizUserErrorMessage = response.data.message; this.users = ["" ]; } }) .catch(error => { this.error = error.message; }); }, onSearch: function (page) { var urlParameters = "?" + tools.objectToQueryString({ __pageNumber: page, __pageSize: tools.getValue("selPageSize"), UserName: txtSearch.value, OrderByType: 1 }); this.fetchData(urlParameters); }, selectAll: function (event) { if (event.target.checked) { // 全选 this.selectedItems = this.data.Data.map(item => item.Id); } else { // 全不选 this.selectedItems = []; } }, deleteAndConfirm: function (item) { if (item == null) { var url = "/PrivateReZeroRoute/100003/DeleteTokenManage?Id=" + localStorage.delId; axios.get(url, jwHeader) .then(response => { if (response.data.message) { tools.alert(response.data.message); } this.data = response.data; this.error = null; this.onSearch(); btnDelClose.click(); }) .catch(error => { this.error = error.message; this.data = null; }); } else { localStorage.delId = item.Id; } }, openEditDiv: function (item) { var th = this; this.title = "修改JWT Token"; this.isReadOnly = true; // 设置只读状态 var urlById = "/PrivateReZeroRoute/100003/GetTokenManageById?id=" + item.Id; if (item.Id) { axios.get(urlById, jwHeader) .then(response => { th.formData = response.data; th.formData.Expiration = tools.formatDate(th.formData.Expiration); }) .catch(error => { this.error = error.message; this.data = null; }); } }, openAddDiv: function () { this.title = "添加JWT Token"; this.isReadOnly = false; // 取消只读状态 this.formData = { Id: 0, UserName: '', Description: '', Expiration: '', Token: '' }; btnSave.click(); }, addOrUpdate: function () { var formData = this.formData; var url = formData.Id ? "/PrivateReZeroRoute/100003/UpdateTokenManage" : "/PrivateReZeroRoute/100003/AddTokenManage"; axios.post(url, formData, jwHeader) .then(response => { if (response.data == true) { btnCloseEdit.click(); this.error = null; this.onSearch(); } else { tools.alert(response.data.message); } }) .catch(error => { this.error = error.message; }); }, copyToClipboard: function (text) { tools.copyText(text); } } }); ``` -------------------------------- ### SQL Script Interface with Parameterization and Pagination Source: https://context7.com/dotnetnext/rezero/llms.txt Execute SQL scripts directly through the ReZero UI. Supports parameterized queries for security, conditional WHERE clauses using [[ ]], and automatic pagination when ResultType is set to PageQuery. ```sql -- 在 ReZero UI「创建接口」→「SQL脚本」中填入以下 SQL -- 示例 1:带参数的查询(@参数名 自动绑定请求体中同名字段) SELECT id, name, amount, created_at FROM orders WHERE user_id = @userId [[AND status = @status]] -- [[ ]] 内的条件:@status 为空时自动忽略此 WHERE 条件 ORDER BY created_at DESC -- 接口参数配置: -- userId: long(必填) -- status: string(可选,空值时 [[AND status = @status]] 被移除) ``` ```sql -- 示例 2:分页查询(ResultType 选择 PageQuery,框架自动处理分页) SELECT id, name, amount FROM orders WHERE user_id = @userId ORDER BY id DESC -- 请求体自动支持 pageNumber(页码)和 pageSize(每页条数) ``` -------------------------------- ### Automatic Dependency Injection Registration with Lifecycle Interfaces Source: https://context7.com/dotnetnext/rezero/llms.txt Implement lifecycle interfaces (IScopeContract, ISingletonContract, ITransientContract) to have ReZero automatically scan and register services. Supports constructor and property injection. ```csharp // 1. 按生命周期接口自动注册 public interface IOrderService { List GetAll(); } // Scoped(每次请求一个实例) public class OrderService : IOrderService, IScopeContract { public List GetAll() => new List { new Order { Id = 1, Name = "订单A" } }; } // Singleton(单例) public class ConfigService : ISingletonContract { public string AppName => "MyApp"; } // Transient(每次注入新实例) public class LogService : ITransientContract { public void Log(string msg) => Console.WriteLine($"[LOG] {msg}"); } ``` ```csharp // 2. 属性注入([DI] 特性,适用于无法使用构造函数注入的场景) [Api(200100)] public class OrderApiService { [DI] // 等价于 [PropertyInjection] public IOrderService OrderService { get; set; } [DI] public LogService LogService { get; set; } [ApiMethod("查询所有订单")] public List GetAllOrders() { LogService.Log("查询所有订单"); return OrderService.GetAll(); } } ``` ```csharp // 3. 注册程序集(在 Program.cs 中指定包含上述类的程序集) builder.Services.AddReZeroServices(api => { var apiObj = SuperAPIOptions.GetOptions(); // 传入多个程序集 apiObj!.DependencyInjectionOptions = new DependencyInjectionOptions( Assembly.GetExecutingAssembly(), typeof(ExternalService).Assembly ); api.EnableSuperApi(apiObj); }); ``` -------------------------------- ### Open SQL Tool Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Initializes and opens the SQL tool interface. Configures Ace Editor for SQL mode with various autocompletion options and sets a twilight theme. Clears the editor content. ```javascript var editor = ace.edit("divAceEditor"); editor.setOption("showPrintMargin", false); editor.setTheme("ace/theme/twilight"); // 设置主题 editor.getSession().setMode("ace/mode/sql"); // 设置语言模式为SQL editor.setOption("enableBasicAutocompletion", true); editor.setOption("enableSnippets", true); editor.setOption("enableLiveAutocompletion", true) editor.setValue("\r\n"); editor.selection.clearSelection(); this.bindSqlResult(); btnDatabaseTool.click(); ``` -------------------------------- ### Register ReZero Services in ASP.NET Core Source: https://context7.com/dotnetnext/rezero/llms.txt Integrates ReZero services into the ASP.NET Core DI container. Use the Action overload for recommended configuration, including enabling SuperAPI and setting up dependency injection with business assemblies. The ReZeroOptions overload is suitable for pure IOC integration without the SuperAPI UI. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // 方式一:通过 Action 配置(推荐) builder.Services.AddReZeroServices(api => { // GetOptions() 从 appsettings.json 的 "ReZero" 节点读取数据库/JWT/Cors 等配置 var apiObj = SuperAPIOptions.GetOptions(); // 注册业务程序集,用于 IOC 自动扫描和代码接口 apiObj!.DependencyInjectionOptions = new DependencyInjectionOptions(Assembly.GetExecutingAssembly()); // 启用超级 API api.EnableSuperApi(apiObj); }); // 方式二:通过 ReZeroOptions 直接配置(适用于纯 IOC 集成,不启用 SuperAPI UI) builder.Services.AddReZeroServices(new ReZeroOptions() { DependencyInjectionOptions = new DependencyInjectionOptions(typeof(Program).Assembly) }); var app = builder.Build(); app.UseAuthorization(); app.MapControllers(); app.Run(); // 启动后访问 http://localhost:5267/rezero 进入 ReZero 管理界面 ``` -------------------------------- ### Vue Instance Initialization and Data Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Initializes the Vue instance for the entity manager, defining data properties, and lifecycle hooks. ```javascript var vueObj = new Vue({ el: '#apibox', data: { databaseId: 0, data: null, error: null, addTitle: "添加实体", editTitle: "修改实体", title: "", sort: 0, sortName: null, sortClass: "", editTable: "", formData: {}, database: [\]], nativeTypes: [\]], selectedItems: [\]], selectedTables: [\]], columns: [{}] , currentColumn: {}, columnsCompareResult: null, tables: [\]], allTables: [\]], tableName: null, editTableId: 0, setting: { importUnunderline: false }, templates: [\]], currentTemplate: {}, currentTemplateId: 0, isView: false, viewName: null, tempUrl: "/rezero/template.html", reviewClass: null }, mounted() { this.bindDatabaseSelect(); this.bindNativeTypeSelect(); this.bindTemplates(); this.bindTempUrl(); }, methods: { fetchData(append) { var url = "/PrivateReZeroRoute/100003/GetEntityInoList?random=1" + append; axios.get(url, jwHeader) .then(response => { this.data = response.data; this.error = null; }) .catch(error => { this.error = error.message; this.data = null; }); }, bindTempUrl: function () { var urlParams = new URLSearchParams(window.location.search); var model = urlParams.get('model'); var token = urlParams.get('token'); if (model) { this.tempUrl += `?model=${model}`; } if (token) { this.tempUrl += model ? `&token=${token}` : `?token=${token}`; } }, onSearch: function (page) { var urlParameters = "&" + tools.objectToQueryString({ ClassName: txtSearch.value, __pageNumber: page, __pageSize: tools.getValue("selPageSize"), DataBaseId: selDataBaseId.value, OrderByType: this.sort, OrderByName: this.sortName }); this.fetchData(urlParameters); }, deleteAndConfirm: function (item) { if (item == null) { var url = "/PrivateReZeroRoute/100003/DeleteEntityInfo?IsDeleted=true&Id=" + localStorage.delId; axios.get(url, jwHeader) .then(response => { if (response.data.message) { tools.alert(response.data.message); } this.error = null; this.onSearch(); btnDelClose.click(); }) .catch(error => { this.error = error.message; this.data = null; }); } else { localStorage.delId = item.Id; } }, deleteSelectedEntities: function () { if (!this.selectedItems || this.selectedItems.length === 0) { tools.alert("请先选择要删除的实体"); return; } if (!confirm("确定要删除选中的实体吗?")) { return; } var url = "/PrivateReZeroRoute/100003/DeleteSelectedEntities"; axios.post(url, { ids: this.selectedItems }, jwHeader) .then(response => { if (response.data && response.data.message) { tools.alert(response.data.message); } this.error = null; this.onSearch(); this.selectedItems = []; document.getElementById('check-all').checked = false; }) .catch(error => { this.error = error.message; this.data = null; }); }, openEditDiv: function (item) { var urlById = "/PrivateReZeroRoute/100003/GetEntityInfoById?id=" + item.Id; if (item.Id) { this.title = this.editTitle; axios.get(urlById, jwHeader) .then(response => { this.formData = response.data; }) .catch(error => { this.error = error.message; this.data = null; }); } }, openAddDiv: function (item) { this.title = this.addTitle; this.formData = { DataBaseId: this.databaseId }; }, addOrUpdate: function () { var th = this; var frmId = "frmEdit"; var json = this.formData; var url = json.Id ? "/PrivateReZeroRoute/100003/UpdateEntityInfo" : "/PrivateReZeroRoute/100003/AddEntityInfo"; this.addOrUpdateSubmit(url, json); }, addOrUpdateSubmit: function (url, json) { var th = this; axios.post(url, json, jwHeader) .then(response => { this.error = null; this.onSearch(); if (response.data == true) { frmEdit.reset(); btnCloseEdit.click(); } else { tools.highlightErrorFields(response.data) } }) .catch(error => { this.error = error.message; this.data = null; }); }, bindDatabaseSelect: function () { axios.get("/PrivateReZeroRoute/100004/GetDatabaseInfoAllList", jwHeader) .then(response => { this.database = response.data; this.databaseId = this.database[0].Id; var th = this; setTimeout(function () { th.onSearch(); }, 50); }) .catch(error => { this.error = error.message; this.data = null; }); }, bindNativeTypeSelect: function () { axios.get("/PrivateReZeroRoute/100004/GetNativeTypeList", jwHeader) .then(response => { this.nativeTypes = response.data; }) .catch(error => { this.error = error.message; this.data = null; }); }, openColumns: function (item) { btnEditColumns.click(); this.editTableId = item.Id; this.editTable = item.ClassName + " - " + item.DataBaseName; var url = "/PrivateReZeroRoute/100003/GetEntityColuminsByEntityId?TableId=" + item.Id; axios.get(url, jwHeader) .then(response => { this.columns = response.data; if (this.columns.length == 0) { this.columns.push({ TableId: item.Id }); } }) .catch(error => { this.error = error.message; }); //初始化拖拽 let _that = this; _that.initDrag(); }, openEditNativeType: function (item) { this.currentColumn = item; btnEditNativeType.click(); }, addOrUpdateColumnInfoSubmit: function () { var url = "/PrivateReZeroRoute/100003/SaveEntityColumnInfos" var th = this; axios.post(url, { Columns: this.columns }, jwHeader) .then(response => { this.erro ``` -------------------------------- ### Configure Rezero API with One Line of Code Source: https://github.com/dotnetnext/rezero/blob/master/README.md Integrate Rezero into a .NET 6+ WEB API project by adding a single line of code during service registration. This configuration does not affect existing code. ```csharp /***对现有代码没有任何影响***/ //注册:注册超级API服务 builder.Services.AddReZeroServices(api => { //启用超级API //有重载可换json文件 var apiObj = new ReZero.SuperAPI.SuperAPIOptions(); //注册DLL apiObj!.DependencyInjectionOptions = new ReZero.SuperAPI.DependencyInjectionOptions(Assembly.GetExecutingAssembly()); //启用超级API api.EnableSuperApi(apiObj); }); //写在builder.Build前面就行只需要一行 var app = builder.Build(); ``` -------------------------------- ### appsettings.json - ReZero Configuration Node Source: https://context7.com/dotnetnext/rezero/llms.txt Centralizes all runtime configurations for ReZero, including database settings, UI preferences, JWT authorization, and CORS policies. These settings are automatically read by SuperAPIOptions.GetOptions(). ```APIDOC ## appsettings.json - ReZero Configuration Node ### Description All runtime configurations for ReZero are consolidated within the `ReZero` node in `appsettings.json`. This includes basic database connection, UI settings, JWT authorization, and cross-origin resource sharing (CORS) configurations. These settings are automatically loaded by `SuperAPIOptions.GetOptions()`. ### Configuration Structure ```json { "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:65000" } } }, "ReZero": { "BasicDatabase": { // DbType supports: MySql | SqlServer | Sqlite | Oracle | PostgreSQL | Dm (DM) | Kdbndp (Kingsoft) "DbType": "Sqlite", "ConnectionString": "datasource=rezero.db" }, "Ui": { // true: Displays ReZero interfaces in Swagger documentation; false: Only displays in ReZero UI "ShowNativeApiDocument": false }, "Jwt": { "Enable": true, "Secret": "C0mPl3xS3cr3tK3yF0rJWT@PROD", "UserTableName": "UserTable", // User table name (can be created in ReZero entity management) "UserNameFieldName": "username", // Username field "PasswordFieldName": "password", // Password field "Expires": 1440, // Token validity period (minutes) "DisableSystemInterface": false, // true: Disables all built-in system interfaces (e.g., table/interface creation) "Claim": [ { "Key": "Id", "FieldName": "Id", "Type": "long" }, { "Key": "Role", "FieldName": "Role", "Type": "string" } ] }, "Cors": { "Enable": true, "PolicyName": "cors", "Headers": ["*"], "Methods": ["*"], "AllowCredentials": false, "Origins": ["http://localhost:3000", "https://yourfrontend.com"] } } } ``` ### Configuration Sections * **BasicDatabase**: Specifies the database type and connection string. * **Ui**: Controls the visibility of ReZero interfaces in Swagger. * **Jwt**: Configures JWT authentication, including secret key, user table details, and claims. * **Cors**: Enables and configures Cross-Origin Resource Sharing policies. ``` -------------------------------- ### Open Copy Functionality Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Triggers the binding of all tables and simulates a click on the 'btnCopy' element. ```javascript openCopy: function () { this.bindAllTables(); btnCopy.click(); } ``` -------------------------------- ### ReZero Configuration in appsettings.json Source: https://context7.com/dotnetnext/rezero/llms.txt Centralizes all runtime configurations for ReZero, including database connection, UI settings, JWT authorization, and CORS policies. These settings are automatically read by SuperAPIOptions.GetOptions(). ```json { "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:65000" } } }, "ReZero": { "BasicDatabase": { // 支持:MySql | SqlServer | Sqlite | Oracle | PostgreSQL | Dm(达梦)| Kdbndp(人大金仓) "DbType": "Sqlite", "ConnectionString": "datasource=rezero.db" }, "Ui": { // true:在 Swagger 文档中也显示 ReZero 接口;false:仅 ReZero UI 中显示 "ShowNativeApiDocument": false }, "Jwt": { "Enable": true, "Secret": "C0mPl3xS3cr3tK3yF0rJWT@PROD", "UserTableName": "UserTable", // 用户表名(可在 ReZero 实体管理中创建) "UserNameFieldName": "username", // 用户名字段 "PasswordFieldName": "password", // 密码字段 "Expires": 1440, // Token 有效期(分钟) "DisableSystemInterface": false, // true 时禁用所有系统内置接口(建表/建接口等) "Claim": [ { "Key": "Id", "FieldName": "Id", "Type": "long" }, { "Key": "Role", "FieldName": "Role", "Type": "string" } ] }, "Cors": { "Enable": true, "PolicyName": "cors", "Headers": ["*"], "Methods": ["*"], "AllowCredentials": false, "Origins": ["http://localhost:3000", "https://yourfrontend.com"] } } } ``` -------------------------------- ### Save License Configuration Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/sys_config.html Saves the license configuration by sending a POST request to '/PrivateReZeroRoute/100003/SaveLicenseConfig' with the license data. It shows a success alert and reloads the current page upon completion. ```javascript saveLicenseConfig() { var th = this; axios.post('/PrivateReZeroRoute/100003/SaveLicenseConfig', { license: this.licenseConfig.License }, jwHeader) .then(() => { tools.alert('保存成功'); window.location.href = window.location.href; }); } ``` -------------------------------- ### Open Generate Code by View Source: https://github.com/dotnetnext/rezero/blob/master/SuperAPI/wwwroot/rezero/default_ui/entity_manager.html Opens the code generation dialog specifically for views. Sets a flag to indicate view generation and triggers the file generation process. ```javascript openGenerateCodeByView: function () { this.isView = true; btnGenerateFile.click(); } ``` -------------------------------- ### Generate ReZero APIs with Code Attributes Source: https://context7.com/dotnetnext/rezero/llms.txt Define APIs by annotating C# classes and methods with `[Api]` and `[ApiMethod]` attributes. ReZero automatically scans assemblies and registers these methods as dynamic interfaces, suitable for a code-first development approach. ```csharp using ReZero.SuperAPI; // [Api] 指定分类 ID(在 ReZero UI「接口分类」中查看对应 ID) [Api(200100)] public class OrderApiService { // [ApiMethod] 描述接口名称,HttpMethod 默认 Post [ApiMethod("获取订单列表")] public List GetOrders(int pageIndex, int pageSize) { // 业务逻辑 return new List { new Order { Id = 1, Name = "订单A", Amount = 100.0m }, new Order { Id = 2, Name = "订单B", Amount = 200.0m } }; } // GET 方法 + URL 参数路由([UrlParameters] 将参数映射到路径段) [ApiMethod("根据ID获取订单")] [ApiMethod("根据ID获取订单", HttpMethod = HttpType.Get)] [UrlParameters] // 生成路由:/api/200100/orderapiservice/getorderbyid/{id} public Order GetOrderById(long id) { return new Order { Id = id, Name = $"订单{id}", Amount = 99.0m }; } // 使用 Post + 自定义 URL [ApiMethod("创建订单")] // Url 属性可自定义路由,不指定则自动生成 public bool CreateOrder(CreateOrderRequest request) { // 保存订单... return true; } } public class Order { public long Id { get; set; } public string Name { get; set; } public decimal Amount { get; set; } } public class CreateOrderRequest { public string Name { get; set; } public decimal Amount { get; set; } } // 调用示例(curl) // POST /api/200100/orderapiservice/getorders // Content-Type: application/json // { "pageIndex": 1, "pageSize": 10 } // GET /api/200100/orderapiservice/getorderbyid/42 ```