Browse Source

Merge branch 'dev' into auto-merge/rel-10-2/4435

pull/25109/head
maliming 5 months ago
parent
commit
af7e6e6f32
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 1
      .gitignore
  2. 26
      Directory.Packages.props
  3. 4
      common.props
  4. 242
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/POST.md
  5. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/ai-management-openai-anythingllm.png
  6. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/chat-playground.png
  7. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/cover-image.png
  8. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/file-management-rba.png
  9. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/mcp-servers.png
  10. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/rag-embedder.png
  11. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/rag-file-upload.png
  12. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/rag-vector-store.png
  13. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/studio-switch-to-preview.png
  14. BIN
      docs/en/Blog-Posts/2026-02-25 v10_2_Preview/test-connection.png
  15. 227
      docs/en/Community-Articles/2026-03-09-Automate-Localhost-Access-for-Expo/POST.md
  16. 201
      docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/POST.md
  17. BIN
      docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/add-permission-dialog.png
  18. BIN
      docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/book-list.png
  19. BIN
      docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/cover.jpeg
  20. BIN
      docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/delete-permission-confirm.png
  21. BIN
      docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/resource-permission-dialog.png
  22. BIN
      docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/update-permission-dialog.png
  23. 252
      docs/en/Community-Articles/2026-03-10-Operation-Rate-Limiting-in-ABP-Framework/POST.md
  24. BIN
      docs/en/Community-Articles/2026-03-10-Operation-Rate-Limiting-in-ABP-Framework/cover.jpeg
  25. 113
      docs/en/Community-Articles/2026-03-10-Tutorial-Validator/article.md
  26. BIN
      docs/en/Community-Articles/2026-03-10-Tutorial-Validator/docs/images/image-1.png
  27. BIN
      docs/en/Community-Articles/2026-03-10-Tutorial-Validator/docs/images/image-2.png
  28. BIN
      docs/en/Community-Articles/2026-03-10-Tutorial-Validator/docs/images/image.png
  29. 185
      docs/en/Community-Articles/2026-03-12-OpenIddict-private-key-jwt/POST.md
  30. BIN
      docs/en/Community-Articles/2026-03-12-OpenIddict-private-key-jwt/cover.png
  31. BIN
      docs/en/Community-Articles/2026-03-12-OpenIddict-private-key-jwt/create-edit-ui.png
  32. 151
      docs/en/Community-Articles/2026-03-17-OpenAI-Compatible-Endpoints/POST.md
  33. BIN
      docs/en/Community-Articles/2026-03-17-OpenAI-Compatible-Endpoints/cover-image.png
  34. BIN
      docs/en/Community-Articles/2026-03-17-OpenAI-Compatible-Endpoints/openai-compatible-endpoints-demo.gif
  35. 167
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/POST.md
  36. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/cover.png
  37. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/exist-user-accept.png
  38. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/invite-admin-user-to-join-tenant-modal.png
  39. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/invite-admin-user-to-join-tenant.png
  40. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/invite-user.png
  41. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/new-user-accept.png
  42. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/new-user-join-strategy-create-tenant.png
  43. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/new-user-join-strategy-inform.png
  44. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/switch-tenant.png
  45. BIN
      docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/tenant-selection.png
  46. 94
      docs/en/cli/index.md
  47. 168
      docs/en/contribution/angular-ui.md
  48. 4
      docs/en/docs-nav.json
  49. 4
      docs/en/framework/infrastructure/background-jobs/tickerq.md
  50. 8
      docs/en/framework/infrastructure/background-workers/tickerq.md
  51. 90
      docs/en/framework/infrastructure/entity-cache.md
  52. 564
      docs/en/framework/infrastructure/operation-rate-limiting.md
  53. 82
      docs/en/framework/ui/angular/extensions-overall.md
  54. 142
      docs/en/framework/ui/angular/pwa-configuration.md
  55. 4
      docs/en/low-code/custom-endpoints.md
  56. 94
      docs/en/low-code/scripting-api.md
  57. 23
      docs/en/package-version-changes.md
  58. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-add-new-standard-module-ui-dialog-blazor-webapp.png
  59. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-add-package-reference-dialog-3-blazor-webapp.png
  60. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-catalog-module-expanded-in-solution-explorer-blazor-webapp.png
  61. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-imports-and-dependencies-v2-blazor-webapp.png
  62. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-install-module-dialog-blazor-webapp.png
  63. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-install-module-dialog-for-ordering-v2-blazor-webapp.png
  64. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-modular-crm-with-standard-module-blazor-webapp.png
  65. BIN
      docs/en/tutorials/modular-crm/images/abp-studio-module-installation-dialog-for-catalog-blazor-webapp.png
  66. BIN
      docs/en/tutorials/modular-crm/images/catalog-module-vs-code-blazor-webapp.png
  67. BIN
      docs/en/tutorials/modular-crm/images/vscode-catalog-index-razor-blazor-webapp.png
  68. 7
      docs/en/tutorials/modular-crm/index.md
  69. 15
      docs/en/tutorials/modular-crm/part-01.md
  70. 15
      docs/en/tutorials/modular-crm/part-02.md
  71. 90
      docs/en/tutorials/modular-crm/part-03.md
  72. 23
      docs/en/tutorials/modular-crm/part-04.md
  73. 122
      docs/en/tutorials/modular-crm/part-05.md
  74. 53
      docs/en/tutorials/modular-crm/part-06.md
  75. 15
      docs/en/tutorials/modular-crm/part-07.md
  76. 9
      docs/en/tutorials/modular-crm/part-08.md
  77. 2
      framework/Volo.Abp.slnx
  78. 2
      framework/src/Volo.Abp.AspNetCore.Abstractions/Volo/Abp/AspNetCore/AbpAspNetCoreAbstractionsModule.cs
  79. 7
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/AbpApiDefinitionController.cs
  80. 22
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/IXmlDocumentationProvider.cs
  81. 231
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/XmlDocumentationProvider.cs
  82. 224
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs
  83. 7
      framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ProxyScripting/AbpServiceProxyScriptController.cs
  84. 18
      framework/src/Volo.Abp.BackgroundJobs.TickerQ/Volo/Abp/BackgroundJobs/TickerQ/AbpBackgroundJobsTickerQModule.cs
  85. 2
      framework/src/Volo.Abp.BackgroundJobs.TickerQ/Volo/Abp/BackgroundJobs/TickerQ/AbpBackgroundJobsTimeTickerConfiguration.cs
  86. 2
      framework/src/Volo.Abp.BackgroundWorkers.TickerQ/Volo/Abp/BackgroundWorkers/TickerQ/AbpBackgroundWorkersCronTickerConfiguration.cs
  87. 4
      framework/src/Volo.Abp.BackgroundWorkers.TickerQ/Volo/Abp/BackgroundWorkers/TickerQ/AbpTickerQBackgroundWorkerManager.cs
  88. 1
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs
  89. 173
      framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateJwksCommand.cs
  90. 74
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/EntityCacheBase.cs
  91. 26
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/EntityCacheServiceCollectionExtensions.cs
  92. 9
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/EntityCacheWithObjectMapper.cs
  93. 21
      framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/IEntityCache.cs
  94. 8
      framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ActionApiDescriptionModel.cs
  95. 2
      framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ApplicationApiDescriptionModelRequestDto.cs
  96. 16
      framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ControllerApiDescriptionModel.cs
  97. 4
      framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/IApiDescriptionModelProvider.cs
  98. 6
      framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/MethodParameterApiDescriptionModel.cs
  99. 6
      framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ParameterApiDescriptionModel.cs
  100. 6
      framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/PropertyApiDescriptionModel.cs

1
.gitignore

@ -270,6 +270,7 @@ modules/blogging/app/Volo.BloggingTestApp/Logs/*.*
modules/blogging/app/Volo.BloggingTestApp/wwwroot/files/*.*
modules/docs/app/VoloDocs.Web/Logs/*.*
modules/setting-management/app/Volo.Abp.SettingManagement.DemoApp/Logs/*.*
modules/openiddict/app/OpenIddict.Demo.Server/wwwroot/libs/**
templates/module/app/MyCompanyName.MyProjectName.DemoApp/Logs/*.*
templates/module/aspnet-core/host/MyCompanyName.MyProjectName.Blazor.Server.Host/Logs/logs.txt
templates/mvc/src/MyCompanyName.MyProjectName.Web/Logs/*.*

26
Directory.Packages.props

@ -117,10 +117,10 @@
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />
<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="8.14.0" />
<PackageVersion Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.14.0" />
<PackageVersion Include="Microsoft.IdentityModel.Tokens" Version="8.14.0" />
<PackageVersion Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.14.0" />
<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="8.16.0" />
<PackageVersion Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.16.0" />
<PackageVersion Include="Microsoft.IdentityModel.Tokens" Version="8.16.0" />
<PackageVersion Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.16.0" />
<PackageVersion Include="Minio" Version="6.0.5" />
<PackageVersion Include="MongoDB.Driver" Version="3.7.0" />
<PackageVersion Include="NEST" Version="7.17.5" />
@ -132,11 +132,11 @@
<PackageVersion Include="NUglify" Version="1.21.17" />
<PackageVersion Include="Nullable" Version="1.3.1" />
<PackageVersion Include="Octokit" Version="14.0.0" />
<PackageVersion Include="OpenIddict.Abstractions" Version="7.2.0" />
<PackageVersion Include="OpenIddict.Core" Version="7.2.0" />
<PackageVersion Include="OpenIddict.Server.AspNetCore" Version="7.2.0" />
<PackageVersion Include="OpenIddict.Validation.AspNetCore" Version="7.2.0" />
<PackageVersion Include="OpenIddict.Validation.ServerIntegration" Version="7.2.0" />
<PackageVersion Include="OpenIddict.Abstractions" Version="7.3.0" />
<PackageVersion Include="OpenIddict.Core" Version="7.3.0" />
<PackageVersion Include="OpenIddict.Server.AspNetCore" Version="7.3.0" />
<PackageVersion Include="OpenIddict.Validation.AspNetCore" Version="7.3.0" />
<PackageVersion Include="OpenIddict.Validation.ServerIntegration" Version="7.3.0" />
<PackageVersion Include="Oracle.EntityFrameworkCore" Version="10.23.26000" />
<PackageVersion Include="Polly" Version="8.6.3" />
<PackageVersion Include="Polly.Extensions.Http" Version="3.0.0" />
@ -183,10 +183,10 @@
<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.6.3" />
<PackageVersion Include="TencentCloudSDK.Sms" Version="3.0.1273" />
<PackageVersion Include="TimeZoneConverter" Version="7.2.0" />
<PackageVersion Include="TickerQ" Version="10.1.1" />
<PackageVersion Include="TickerQ.Dashboard" Version="10.1.1" />
<PackageVersion Include="TickerQ.Utilities" Version="10.1.1" />
<PackageVersion Include="TickerQ.EntityFrameworkCore" Version="10.1.1" />
<PackageVersion Include="TickerQ" Version="10.2.0" />
<PackageVersion Include="TickerQ.Dashboard" Version="10.2.0" />
<PackageVersion Include="TickerQ.Utilities" Version="10.2.0" />
<PackageVersion Include="TickerQ.EntityFrameworkCore" Version="10.2.0" />
<PackageVersion Include="Unidecode.NET" Version="2.1.0" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.extensibility.execution" Version="2.9.3" />

4
common.props

@ -1,8 +1,8 @@
<Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Version>10.2.0-rc.2</Version>
<LeptonXVersion>5.2.0-rc.2</LeptonXVersion>
<Version>10.3.0-preview</Version>
<LeptonXVersion>5.3.0-preview</LeptonXVersion>
<NoWarn>$(NoWarn);CS1591;CS0436</NoWarn>
<PackageIconUrl>https://abp.io/assets/abp_nupkg.png</PackageIconUrl>
<PackageProjectUrl>https://abp.io/</PackageProjectUrl>

242
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/POST.md

@ -0,0 +1,242 @@
# ABP Platform 10.2 RC Has Been Released
We are happy to release [ABP](https://abp.io) version **10.2 RC** (Release Candidate). This blog post introduces the new features and important changes in this new version.
Try this version and provide feedback for a more stable version of ABP v10.2! Thanks to you in advance.
## Get Started with the 10.2 RC
You can check the [Get Started page](https://abp.io/get-started) to see how to get started with ABP. You can either download [ABP Studio](https://abp.io/get-started#abp-studio-tab) (**recommended**, if you prefer a user-friendly GUI application - desktop application) or use the [ABP CLI](https://abp.io/docs/latest/cli).
By default, ABP Studio uses stable versions to create solutions. Therefore, if you want to create a solution with a preview version, first you need to create a solution and then switch your solution to the preview version from the ABP Studio UI:
![studio-switch-to-preview.png](studio-switch-to-preview.png)
## Migration Guide
There are a few breaking changes in this version that may affect your application. Please read the migration guide carefully, if you are upgrading from v10.1 or earlier: [ABP Version 10.2 Migration Guide](https://abp.io/docs/10.2/release-info/migration-guides/abp-10-2).
## What's New with ABP v10.2?
In this section, I will introduce some major features released in this version.
Here is a brief list of titles explained in the next sections:
- Multi-Tenant Account Usage: Shared User Accounts
- Prevent Privilege Escalation: Assignment Restrictions for Roles and Permissions
- `ClientResourcePermissionValueProvider` for OAuth/OpenIddict
- Angular: Hybrid Localization Support
- Angular: Extensible Table Row Detail
- Angular: CMS Kit Module Features
- Blazor: Upgrade to Blazorise 2.0
- Identity: Single Active Token Providers
- TickerQ Package Upgrade to 10.1.1
- AI Management: MCP (Model Context Protocol) Support
- AI Management: RAG with File Upload
- AI Management: OpenAI-Compatible Chat Endpoint
- File Management: Resource-Based Authorization
### Multi-Tenant Account Usage: Shared User Accounts
ABP v10.2 introduces **Shared User Accounts**: a single user account can belong to multiple tenants, and the user can choose or switch the active tenant when signing in. This enables a "one account, multiple tenants" experience — for example, inviting the same email address into multiple tenants.
When you use Shared User Accounts:
- Username/email uniqueness becomes **global** (Host + all tenants)
- Users are prompted to select the tenant at login if they belong to multiple tenants
- Users can switch between tenants using the tenant switcher in the user menu
- Tenant administrators can invite existing or new users to join a tenant
Enable shared accounts by configuring `UserSharingStrategy`:
```csharp
Configure<AbpMultiTenancyOptions>(options =>
{
options.IsEnabled = true;
options.UserSharingStrategy = TenantUserSharingStrategy.Shared;
});
```
> See the [Shared User Accounts](https://abp.io/docs/10.2/modules/account/shared-user-accounts) documentation for details.
### Prevent Privilege Escalation: Assignment Restrictions for Roles and Permissions
ABP v10.2 implements a unified **privilege escalation prevention** model to address security vulnerabilities where users could assign themselves or others roles or permissions they do not possess.
**Role Assignment Restriction:** Users can only assign or remove roles they currently have. Users cannot add new roles to themselves (removal only) and cannot assign or remove roles they do not possess.
**Permission Grant/Revoke Authorization:** Users can only grant or revoke permissions they currently have. Validation applies to both grant and revoke operations.
**Incremental Permission Protection:** When updating user or role permissions, permissions the current user does not have are treated as non-editable and are preserved as-is during updates.
Users with the `admin` role can assign any role and grant/revoke any permission. All validations are enforced on the backend — the UI is not a security boundary.
> See [#24775](https://github.com/abpframework/abp/pull/24775) for more details.
### `ClientResourcePermissionValueProvider` for OAuth/OpenIddict
ABP v10.2 adds **ClientResourcePermissionValueProvider**, extending resource-based authorization to OAuth clients. When using IdentityServer or OpenIddict, clients can now have resource permissions aligned with the standard user and role permission model.
This allows you to control which OAuth clients can access which resources, providing fine-grained authorization for API consumers. The implementation integrates with ABP's existing resource permission infrastructure.
> See [#24515](https://github.com/abpframework/abp/pull/24515) for more details.
### Angular: Hybrid Localization Support
ABP v10.2 introduces **Hybrid Localization** for Angular applications, combining server-side and client-side localization strategies. This gives you flexibility in how translations are loaded and resolved — you can use server-provided localization, client-side fallbacks, or a mix of both.
This feature is useful when you want to reduce initial load time, support offline scenarios, or have environment-specific localization behavior. The Angular packages have been updated to support the hybrid approach seamlessly.
> See the [Hybrid Localization](https://abp.io/docs/10.2/framework/ui/angular/hybrid-localization) documentation and [#24731](https://github.com/abpframework/abp/pull/24731).
### Angular: Extensible Table Row Detail
ABP v10.2 adds the **ExtensibleTableRowDetailComponent** for expandable row details in extensible tables. You can now display additional information for each row in a collapsible detail section.
The feature supports row detail templates via both direct input and content child component. It adds toggle logic and emits `rowDetailToggle` events, making it easy to customize the behavior and appearance of expandable rows in your data tables.
> See [#24636](https://github.com/abpframework/abp/pull/24636) for more details.
### Angular: CMS Kit Module Features
ABP v10.2 brings **CMS Kit features to Angular**, completing the cross-platform UI coverage for the CMS Kit module. The Angular implementation includes: Blogs, Blog Posts, Comments, Menus, Pages, Tags, Global Resources, and CMS Settings.
Together with the CMS Kit Pro Angular implementation (FAQ, Newsletters, Page Feedbacks, Polls, Url forwarding), ABP now provides full Angular UI coverage for both the open-source CMS Kit and CMS Kit Pro modules.
> See [#24234](https://github.com/abpframework/abp/pull/24234) for more details.
### Blazor: Upgrade to Blazorise 2.0
ABP v10.2 upgrades the [Blazorise](https://blazorise.com/) library to **version 2.0** for Blazor UI. If you are upgrading your project to v10.2 RC, please ensure that all Blazorise-related packages are updated to v2.0 in your application.
Blazorise 2.0 includes various improvements and changes. Please refer to the [Blazorise 2.0 Release Notes](https://blazorise.com/news/release-notes/200) and the [ABP Blazorise 2.0 Migration Guide](https://abp.io/docs/10.2/release-info/migration-guides/blazorise-2-0-migration) for upgrade instructions.
> See [#24906](https://github.com/abpframework/abp/pull/24906) for more details.
### Identity: Single Active Token Providers
ABP v10.2 introduces a **single active token** policy for password reset, email confirmation, and change-email flows. Three new token providers are available: `AbpPasswordResetTokenProvider`, `AbpEmailConfirmationTokenProvider`, and `AbpChangeEmailTokenProvider`.
When a new token is generated, it invalidates any previously issued tokens for that purpose. This improves security by ensuring that only the most recently issued token is valid. Token lifespan can be customized via the respective options classes for each provider.
> See [#24926](https://github.com/abpframework/abp/pull/24926) for more details.
### TickerQ Package Upgrade to 10.1.1
**If you are using the TickerQ integration packages** (`Volo.Abp.TickerQ`, `Volo.Abp.BackgroundJobs.TickerQ`, or `Volo.Abp.BackgroundWorkers.TickerQ`), you need to apply breaking changes when upgrading to ABP 10.2. TickerQ has been upgraded from 2.5.3 to 10.1.1, which only targets .NET 10.0 and contains several API changes.
Key changes include:
- `UseAbpTickerQ` moved from `IApplicationBuilder` to `IHost` — use `context.GetHost().UseAbpTickerQ()` in your module
- Entity types renamed: `TimeTicker``TimeTickerEntity`, `CronTicker``CronTickerEntity`
- Scheduler and dashboard configuration APIs have changed
- New helpers: `context.GetHost()`, `GetWebApplication()`, `GetEndpointRouteBuilder()`
> **Important:** Do **not** resolve `IHost` from `context.ServiceProvider.GetRequiredService<IHost>()`. Always use `context.GetHost()`. See the [ABP Version 10.2 Migration Guide](https://abp.io/docs/10.2/release-info/migration-guides/abp-10-2) for the complete list of changes.
### AI Management: MCP (Model Context Protocol) Support
_This is a **PRO** feature available for ABP Commercial customers._
The [AI Management Module](https://abp.io/docs/10.2/modules/ai-management) now supports [MCP (Model Context Protocol)](https://modelcontextprotocol.io/), enabling AI workspaces to use external MCP servers as tools. MCP allows AI models to interact with external services, databases, APIs, and more through a standardized protocol.
![mcp-servers](mcp-servers.png)
You can create and manage MCP servers via the AI Management UI. Each MCP server supports one of the following transport types: **Stdio** (runs a local command), **SSE** (Server-Sent Events), or **StreamableHttp**. For HTTP-based transports, you can configure authentication (API Key, Bearer token, or custom headers). Once MCP servers are defined, you can associate them with workspaces. When a workspace has MCP servers associated, the AI model can invoke tools from those servers during chat conversations — tool calls and results are displayed in the chat interface.
You can test the connection to an MCP server after creating it to verify connectivity and list available tools before use:
![test-connection](test-connection.png)
When a workspace has MCP servers associated, the AI model can invoke tools from those servers during chat conversations. Tool calls and results are displayed in the chat interface.
![chat-playground](chat-playground.png)
> See the [AI Management documentation](https://abp.io/docs/10.2/modules/ai-management#mcp-servers) for details.
### AI Management: RAG with File Upload
_This is a **PRO** feature available for ABP Commercial customers._
The AI Management module supports **RAG (Retrieval-Augmented Generation)** with file upload, which enables workspaces to answer questions based on the content of uploaded documents. When RAG is configured, the AI model searches the uploaded documents for relevant information before generating a response.
To enable RAG, configure an **embedder** (e.g., OpenAI, Ollama) and a **vector store** (e.g., PgVector) on the workspace:
| Embedder | Vector Store |
| --- | --- |
| ![rag-embedder](rag-embedder.png) | ![rag-vector-store](rag-vector-store.png) |
You can then upload documents (PDF, Markdown, or text files, max 10 MB) through the workspace management UI. Uploaded documents are automatically processed — their content is chunked, embedded, and stored in the configured vector store:
![rag-file-upload](rag-file-upload.png)
When you ask questions in the chat interface, the AI model uses the uploaded documents as context for accurate, grounded responses.
> See the [AI Management — RAG with File Upload](https://abp.io/docs/10.2/modules/ai-management#rag-with-file-upload) documentation for configuration details.
### AI Management: OpenAI-Compatible Chat Endpoint
_This is a **PRO** feature available for ABP Commercial customers._
The AI Management module exposes an **OpenAI-compatible REST API** at the `/v1` path. This allows any application or tool that supports the OpenAI API format — such as [AnythingLLM](https://anythingllm.com/), [Open WebUI](https://openwebui.com/), [Dify](https://dify.ai/), or custom scripts using the OpenAI SDK — to connect directly to your AI Management instance.
**Example configuration from AnythingLLM**:
![anythingllm](ai-management-openai-anythingllm.png)
Each AI Management **workspace** appears as a selectable model in the client application. The workspace's configured AI provider handles the actual inference transparently. Available endpoints include `/v1/chat/completions`, `/v1/models`, `/v1/embeddings`, `/v1/files`, and more. All endpoints require authentication via a Bearer token in the `Authorization` header.
> See the [AI Management — OpenAI-Compatible API](https://abp.io/docs/10.2/modules/ai-management#openai-compatible-api) documentation for usage examples.
### File Management: Resource-Based Authorization
_This is a **PRO** feature available for ABP Commercial customers._
The **File Management Module** now supports **resource-based authorization**. You can control access to individual files and folders per user, role, or client. Permissions can be granted at the resource level via the UI, and the feature integrates with ABP's resource permission infrastructure.
![file-management-resource-based-authorization](file-management-rba.png)
This feature is **implemented for all three supported UIs: MVC/Razor Pages, Blazor, and Angular**, providing a consistent experience across your application regardless of the UI framework you use.
### Other Improvements and Enhancements
- **Angular signal APIs**: ABP Angular packages migrated to signal queries, output functions, and signal input functions for alignment with Angular 21 ([#24765](https://github.com/abpframework/abp/pull/24765), [#24766](https://github.com/abpframework/abp/pull/24766), [#24777](https://github.com/abpframework/abp/pull/24777)).
- **Angular Vitest**: ABP Angular templates now use Vitest as the default testing framework instead of Karma/Jasmine ([#24725](https://github.com/abpframework/abp/pull/24725)).
- **Ambient auditing**: Programmatic disable/enable of auditing via `IAuditingHelper.DisableAuditing()` and `IsAuditingEnabled()` ([#24718](https://github.com/abpframework/abp/pull/24718)).
- **Complex property auditing**: Entity History and ModifierId now support EF Core complex properties ([#24767](https://github.com/abpframework/abp/pull/24767)).
- **RabbitMQ correlation ID**: Correlation ID support added to RabbitMQ JobQueue for distributed tracing ([#24755](https://github.com/abpframework/abp/pull/24755)).
- **Concurrent config retrieval**: `MvcCachedApplicationConfigurationClient` now fetches configuration and localization concurrently for faster startup ([#24838](https://github.com/abpframework/abp/pull/24838)).
- **Environment localization fallback**: Angular can use `environment.defaultResourceName` when the backend does not provide it ([#24589](https://github.com/abpframework/abp/pull/24589)).
- **JS proxy namespace fix**: Resolved namespace mismatch for multi-segment company names in generated proxies ([#24877](https://github.com/abpframework/abp/pull/24877)).
- **Audit Logging max length**: Entity/property type full names increased to 512 characters to reduce truncation ([#24846](https://github.com/abpframework/abp/pull/24846)).
- **AI guidelines**: Cursor and Copilot AI guideline documents added for ABP development ([#24563](https://github.com/abpframework/abp/pull/24563), [#24593](https://github.com/abpframework/abp/pull/24593)).
## Community News
### New ABP Community Articles
As always, exciting articles have been contributed by the ABP community. I will highlight some of them here:
- [Enis Necipoğlu](https://abp.io/community/members/enisn) has published 2 new posts:
- [ABP Framework's Hidden Magic: Things That Just Work Without You Knowing](https://abp.io/community/articles/hidden-magic-things-that-just-work-without-you-knowing-vw6osmyt)
- [Implementing Multiple Global Query Filters with Entity Framework Core](https://abp.io/community/articles/implementing-multiple-global-query-filters-with-entity-ugnsmf6i)
- [Suhaib Mousa](https://abp.io/community/members/suhaib-mousa) has published 2 new posts:
- [.NET 11 Preview 1 Highlights: Faster Runtime, Smarter JIT, and AI-Ready Improvements](https://abp.io/community/articles/dotnet-11-preview-1-highlights-hspp3o5x)
- [TOON vs JSON for LLM Prompts in ABP: Token-Efficient Structured Context](https://abp.io/community/articles/toon-vs-json-b4rn2avd)
- [Fahri Gedik](https://abp.io/community/members/fahrigedik) has published 2 new posts:
- [Building a Multi-Agent AI System with A2A, MCP, and ADK in .NET](https://abp.io/community/articles/building-a-multiagent-ai-system-with-a2a-mcp-iefdehyx)
- [Async Chain of Persistence Pattern: Designing for Failure in Event-Driven Systems](https://abp.io/community/articles/async-chain-of-persistence-pattern-wzjuy4gl)
- [Alper Ebiçoğlu](https://abp.io/community/members/alper) has published 2 new posts:
- [NDC London 2026: From a Developer's Perspective and My Personal Notes about AI](https://abp.io/community/articles/ndc-london-2026-a-.net-conf-from-a-developers-perspective-07wp50yl)
- [Which Open-Source PDF Libraries Are Recently Popular? A Data-Driven Look At PDF Topic](https://abp.io/community/articles/which-opensource-pdf-libraries-are-recently-popular-a-g68q78it)
- [Stop Spam and Toxic Users in Your App with AI](https://abp.io/community/articles/stop-spam-and-toxic-users-in-your-app-with-ai-3i0xxh0y) by [Engincan Veske](https://abp.io/community/members/EngincanV)
- [How AI Is Changing Developers](https://abp.io/community/articles/how-ai-is-changing-developers-e8y4a85f) by [Liming Ma](https://abp.io/community/members/maliming)
- [JetBrains State of Developer Ecosystem Report 2025 — Key Insights](https://abp.io/community/articles/jetbrains-state-of-developer-ecosystem-report-2025-key-z0638q5e) by [Tarık Özdemir](https://abp.io/community/members/mtozdemir)
- [Integrating AI into ABP.IO Applications: The Complete Guide to Volo.Abp.AI and AI Management Module](https://abp.io/community/articles/integrating-ai-into-abp.io-applications-the-complete-guide-jc9fbjq0) by [Adnan Ali](https://abp.io/community/members/adnanaldaim)
Thanks to the ABP Community for all the content they have published. You can also [post your ABP related (text or video) content](https://abp.io/community/posts/create) to the ABP Community.
## Conclusion
This version comes with some new features and a lot of enhancements to the existing features. You can see the [Road Map](https://abp.io/docs/10.2/release-info/road-map) documentation to learn about the release schedule and planned features for the next releases. Please try ABP v10.2 RC and provide feedback to help us release a more stable version.
Thanks for being a part of this community!

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/ai-management-openai-anythingllm.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/chat-playground.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/cover-image.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 458 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/file-management-rba.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/mcp-servers.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/rag-embedder.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/rag-file-upload.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/rag-vector-store.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/studio-switch-to-preview.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
docs/en/Blog-Posts/2026-02-25 v10_2_Preview/test-connection.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

227
docs/en/Community-Articles/2026-03-09-Automate-Localhost-Access-for-Expo/POST.md

@ -0,0 +1,227 @@
# Automate Localhost Access for Expo: A Guide to Dynamic Cloudflare Tunnels & Dev Builds
Every mobile developer eventually hits the "Localhost Wall." You have built a brilliant API on your machine, and your React Native app works perfectly in the iOS Simulator or Android Emulator. But the moment you pick up a physical device to test real-world performance or camera features, everything breaks.
### The Problem: Why Your Phone Can’t See localhost
When you run a backend server on your computer, localhost refers to the "loopback" address and essentially, the computer talking to itself. Your physical iPhone or Android device is a separate node on the network. From its perspective, localhost is itself, not your development machine. Without a direct bridge, your mobile app is shouting into a void, unable to reach the API sitting just inches away on your desk.
### The Conflict: The Fragility of Local IP Addresses
The traditional workaround is to find the local IP address of your device and hardcode it into your app. However, this approach has many obstacles that make it difficult to use:
- **Network Volatility:** Your router might assign you a new IP address tomorrow, forcing you to update your code constantly.
- **The SSL Headache:** Modern mobile operating systems and many OAuth providers (like Google or Auth0) strictly require **HTTPS**. Running a local development server with valid SSL certificates is a notorious configuration nightmare.
- **Broken OAuth flows:** Most authentication providers refuse to redirect to a non-secure `http` address or a random local IP, effectively locking you out of testing login features on a real device.
### The Solution: Cloudflare Tunnel as a Secure Bridge
This is where **Cloudflare Tunnel** changes the game. Instead of poking holes in your firewall or wrestling with self-signed certificates, Cloudflare Tunnel creates a secure, outbound-only connection between your local machine and the Cloudflare edge.
It provides you with a **public, HTTPS-enabled URL** (e.g., `https://random-word.trycloudflare.com`) that automatically points to your local port. To your mobile device, your local backend looks like a standard, secure production API. It bypasses network restrictions, satisfies SSL requirements, and—when paired with a simple automation script—makes "localhost" development on physical devices completely seamless.
### 1. Architecture Overview
In order to understand why this setup is so effective, it is better to visualize the data flow. Traditionally, your mobile device would try to ping your laptop directly over Wi-Fi that is often blocked by firewalls or complicated by internal IP routing.
#### Workflow Summary: The Secure "Middleman"
The Cloudflare Tunnel acts as a persistent, encrypted bridge between your local environment and the public internet. Here is how the traffic flows in a standard development session:
1. **The Connector:** You run a small `cloudflared` daemon on your development machine. It establishes an **outbound** connection to Cloudflare’s nearest edge server. Because it is outbound, you don't need to open any ports on your home or office router.
2. **The Public Endpoint:** Cloudflare provides a temporary, unique HTTPS URL (e.g., `https://example-tunnel.trycloudflare.com`). This URL is globally accessible.
3. **The Mobile Request:** Your React Native app that is running on a physical iPhone or Android sends an API request to that HTTPS URL. To the phone, this looks like any other secure production website.
4. **The Local Handoff:** Cloudflare receives the request and "tunnels" it down the active connection to your machine. The `cloudflared` tool then forwards that request to your local backend whether it's running on `.NET` at port `44358`, `Node.js` at `3000`, or `Rails` at `3000`.
5. **The Response:** Your backend processes the request and sends the data back through the same tunnel to the phone.
By sitting in the middle, Cloudflare handles the **SSL termination** and the **Global Routing**, ensuring your backend is reachable regardless of whether your phone is on the same Wi-Fi as your laptop.
### 2. Prerequisites
Before we bridge the gap between your mobile device and your local machine, ensure your development environment is equipped with the following core components.
To follow this guide, you will need:
- **Node.js & Package Manager:** A stable version of Node.js (LTS recommended) and either **npm** or **yarn** to manage dependencies and run the automation scripts.
- **Expo CLI:** Ensure you have the latest version of `expo` installed globally or within your project. We will be using this to manage the development server and build the application.
- **Cloudflared CLI:** This is the critical "connector" tool from Cloudflare. You’ll need it installed on your local machine to establish the tunnel.
- *Quick Tip:* You don't need a paid Cloudflare account; the **Quick Tunnels** used in this guide are free and require no login.
- **A Running Backend API:** Your local server (e.g., .NET, Node.js, Django, or Rails) should be active and listening on a specific port (like `44358` or `3000`).
### 3. Step-by-Step Implementation
Now, let’s configure the automation that makes this workflow "set it and forget it."
#### Phase A: Backend Configuration (The OAuth Handshake)
Modern mobile authentication often relies on **OAuth 2.0** or **OpenID Connect**. For the login flow to succeed, your backend must "trust" the redirect URI sent by the mobile app. ABP applications are an example for such handshake.
Even though we are using a Cloudflare URL for the API calls, the `auth-session` of Expo typically generates a `localhost` redirect for development. You must update your backend configuration (e.g., `appsettings.json` in a .NET TemplateTwo setup) to allow this:
**File:** `src/YourProject.DbMigrator/appsettings.json`
```json
{
"OpenIddict": {
"Applications": {
"Mobile_App": {
"ClientId": "Mobile_App",
"RootUrl": "exp://localhost:19000"
}
}
}
}
```
**Note:** By setting the `RootUrl` to `exp://localhost:19000`, you ensure that once the user authenticates via the tunnel's secure page, the mobile OS knows exactly how to hand the token back to your running Expo instance.
#### Phase B: The "Magic" Script (Automating the Tunnel)
The primary headache with free Cloudflare Tunnels is that they generate a **random URL** every time you restart the service. Manually copying `https://shiny-new-url.trycloudflare.com` into your frontend code every morning is a productivity killer.
We solve this with a **Node.js automation script** that launches the tunnel, "listens" to the terminal output to find the new URL, and automatically injects it into your project's configuration.
**File:** `react-native/scripts/tunnel.js`
```js
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
// Target files for automation
const tunnelConfigFile = path.join(__dirname, '..', 'tunnel-config.json');
const environmentFile = path.join(__dirname, '..', 'Environment.ts');
// 1. Launch the Cloudflare Tunnel pointing to your local API port
const cloudflared = spawn('cloudflared', ['tunnel', '--url', 'http://localhost:44358']);
let domainCaptured = false;
cloudflared.stdout.on('data', data => {
const output = data.toString();
console.log(output); // Keep logs visible for debugging
if (!domainCaptured) {
// 2. Regex to catch the dynamic "trycloudflare" URL
const urlMatch = output.match(/https:\/\/([a-z0-9-]+\.trycloudflare\.com)/);
if (urlMatch) {
const domain = urlMatch[1];
// 3. Save to a JSON file for the app to read
fs.writeFileSync(tunnelConfigFile, JSON.stringify({ domain }, null, 2));
// 4. Update the fallback value in Environment.ts directly
let envContent = fs.readFileSync(environmentFile, 'utf8');
envContent = envContent.replace(
/let tunnelDomain = '[^']*'; \/\/ fallback/,
`let tunnelDomain = '${domain}'; // fallback`,
);
fs.writeFileSync(environmentFile, envContent, 'utf8');
console.log(`\n✅ Tunnel Synchronized: ${domain}`);
domainCaptured = true;
}
}
});
```
By capturing the trycloudflare.com domain programmatically, we treat the tunnel like a dynamic environment variable. This ensures that your mobile app, your backend OAuth settings, and your API client stay in perfect sync without a single keystroke from you.
#### Phase C: Environment Integration
To make this work within your React Native code, your `Environment.ts` file needs to be "smart" enough to look for the generated config file. We use a `try/catch` block so the app doesn't crash if the tunnel isn't running.
**File:** `react-native/Environment.ts`
```tsx
let tunnelDomain = 'your-default-fallback.com'; // fallback
try {
// Pull the latest domain from the script's output
const tunnelConfig = require('./tunnel-config.json');
if (tunnelConfig?.domain) {
tunnelDomain = tunnelConfig.domain;
}
} catch (e) {
console.warn('⚠️ No active tunnel config found. Using fallback.');
}
const apiUrl = `https://${tunnelDomain}`;
export const getEnvVars = () => {
return {
apiUrl,
// Other environment variables...
};
};
```
This setup creates a **"Single Source of Truth."** When you run the script, it updates `tunnel-config.json`, and your app instantly points to the correct secure endpoint.
### 4. Integration with Expo Development Builds
While you can technically use the standard **Expo Go** app for basic API testing, professional React Native workflows, especially those involving secure authentication and custom networking, rely on **Expo Development Builds**.
#### Why Development Builds are Essential for This Workflow
Standard Expo Go is a "one-size-fits-all" sandbox. However, as your app grows, it needs to behave more like a real, standalone binary. Development Builds are preferred for two main reasons:
- **Custom URL Schemes:** For OAuth flows (like the one configured in Phase A), your app needs to handle specific deep links (e.g., `myapp://`). Expo Go has its own internal URL handling that can sometimes conflict with complex redirect logic. A Development Build allows you to define your own scheme, ensuring the Cloudflare-tunneled backend knows exactly where to send the user back after login.
- **Native Dependency Control:** If your app uses native modules for secure storage, biometrics, or advanced networking, Expo Go won't support them. A Development Build includes your project's specific native code while still giving you the "hot reloading" developer experience of Expo.
#### Configuring the Build for Tunnelling
To ensure your development build is ready for the Cloudflare tunnel, you'll typically use the `expo-dev-client` package. This transforms your app into a powerful developer tool that can switch between different local or tunneled environments on the fly.
> **Pro Tip:** When you run `npx expo start`, your Development Build will look for the `apiUrl` we configured in `Environment.ts`. Since our script has already injected the Cloudflare URL, the physical device will connect to your local backend through the tunnel the moment the app loads.
### 5. Execution Workflow
To get your entire stack synchronized, follow this specific launch order. This ensures the tunnel is active and the configuration files are updated before the React Native app attempts to read them.
#### Step 1: Start the Backend
Fire up your API (e.g., `.NET`, `Node`, `Go`). Ensure it is listening on the port defined in your `tunnel.js` (e.g., `44358`).
#### Step 2: Launch the Tunnel
In a new terminal, run your automation script.
Wait for the message: `✅ Tunnel Synchronized`. This confirms `tunnel-config.json` has been updated with the new `trycloudflare.com` domain.
#### Step 3: Start Expo
Finally, start your Expo development server:
```bash
npx expo start
```
Open the app on your physical device by scanning the QR code. Your app is now communicating with your local machine over a secure, global HTTPS bridge.
### 6. Troubleshooting & Best Practices
Even with automation, networking can be finicky. If your app isn't reaching the API, check these common roadblocks:
#### Common Pitfalls
- **Port Mismatches:** Ensure the port in your `tunnel.js` script (e.g., `44358`) exactly matches the port your backend is listening on. If your backend uses HTTPS locally, ensure the tunnel command reflects that (e.g., `https://localhost:port`).
- **Firewall & Ghost Processes:** Sometimes a previous `cloudflared` process hangs in the background. If you can't start a new tunnel, kill existing processes or check if your local firewall is blocking `cloudflared` from making outbound connections.
- **Expired Sessions:** Free "Quick Tunnels" are temporary. If you leave your computer on overnight, the tunnel might disconnect. Simply restart the script to generate a fresh, synced URL.
#### Security Note
Cloudflare Tunnels create a **publicly accessible URL**. While the random strings in `trycloudflare.com` provide "security through obscurity," anyone with that link can hit your local API.
- **Development Data Only:** Never use this setup with production databases or sensitive PII (Personally Identifiable Information).
- **Disable When Idle:** Close the tunnel terminal when you aren't actively developing to shut the "bridge" to your machine.
### 7. Conclusion & Future-Proofing
By replacing hardcoded local IPs with a dynamic Cloudflare Tunnel, you’ve transformed a clunky, manual process into a **"Set it and forget it"** workflow. You no longer have to worry about shifting Wi-Fi addresses or SSL certificate errors on physical devices. Your development environment now mirrors the behavior of a production app, providing more accurate testing and faster debugging.
#### The Road to Production: EAS
This tunneling strategy is the perfect companion for **EAS (Expo Application Services)**. As you move toward testing internal distributions, you can use these same environment patterns to point your EAS-built binaries to various staging or development endpoints.
With a secure bridge and an automated config, you are no longer tethered to a simulator. Grab your phone, head to a coffee shop, and keep building—your backend is now globally (and securely) following you.

201
docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/POST.md

@ -0,0 +1,201 @@
# Resource-Based Authorization in ABP Framework
ABP has a built-in permission system that supports role-based access control (RBAC). You define permissions, assign them to roles, and assign roles to users — once a user logs in, they automatically have the corresponding access. This covers the vast majority of real-world scenarios and is simple, straightforward, and easy to maintain.
However, there is one class of requirements it cannot handle: **different access rights for different instances of the same resource type**.
Take a bookstore application as an example. You define a `Books.Edit` permission and assign it to an editor role, so every editor can modify every book. But reality is often more nuanced:
- A specific book should only be editable by its assigned editor
- Certain books are only visible to specific users
- Different users have different levels of access to the same book
Standard permissions cannot address this, because their granularity is the *permission type*, not a *specific record*. The traditional approach requires designing your own database tables, writing query logic, and building a management UI from scratch — all of which is costly.
ABP Framework now ships with **Resource-Based Authorization** to solve exactly this problem. The core idea is to bind permissions to specific resource instances rather than just resource types. For example, you can grant a user permission to edit the price of *1984* specifically, while they have no access to any other book.
More importantly, the entire permission management workflow is handled through a built-in UI dialog — **no custom code needed for the management side**.
## How It Works
Each resource instance (e.g. a book) can have its own permission management dialog. Users who hold the `ManagePermissions` permission can open it and grant or revoke access for users, roles, or OAuth clients — all from the UI.
A **Permissions** action appears in each book's action menu:
![book-list](./book-list.png)
Clicking it opens the resource permission management dialog for that specific book. You can see who currently has access and click **Add permission** to grant more:
![resource-permission-dialog](./resource-permission-dialog.png)
The **Add permission** dialog lets you select a user, role, or OAuth client, then choose which permissions to grant:
![add-permission-dialog](./add-permission-dialog.png)
After saving, the new entry appears in the list immediately.
Each entry in the list also supports **Edit** and **Delete** actions. Clicking **Edit** opens the update dialog where you can adjust the granted permissions:
![update-permission-dialog](./update-permission-dialog.png)
Clicking **Delete** shows a confirmation prompt — confirming removes all permissions for that user, role, or OAuth client on this book:
![delete-permission-confirm](./delete-permission-confirm.png)
## Setting It Up
To get this working, you need to define your resource permissions and wire up the dialog.
### Defining Resource Permissions
```csharp
public static class BookStorePermissions
{
public const string GroupName = "BookStore";
public static class Books
{
public const string Default = GroupName + ".Books";
public const string ManagePermissions = Default + ".ManagePermissions";
public static class Resources
{
public const string Name = "Acme.BookStore.Books.Book";
public const string View = Name + ".View";
public const string Edit = Name + ".Edit";
public const string Delete = Name + ".Delete";
}
}
}
```
```csharp
public override void Define(IPermissionDefinitionContext context)
{
var group = context.AddGroup(BookStorePermissions.GroupName);
var bookPermission = group.AddPermission(BookStorePermissions.Books.Default);
// Users with this permission can open the resource permission dialog
bookPermission.AddChild(BookStorePermissions.Books.ManagePermissions);
context.AddResourcePermission(
name: BookStorePermissions.Books.Resources.View,
resourceName: BookStorePermissions.Books.Resources.Name,
managementPermissionName: BookStorePermissions.Books.ManagePermissions
);
context.AddResourcePermission(
name: BookStorePermissions.Books.Resources.Edit,
resourceName: BookStorePermissions.Books.Resources.Name,
managementPermissionName: BookStorePermissions.Books.ManagePermissions
);
context.AddResourcePermission(
name: BookStorePermissions.Books.Resources.Delete,
resourceName: BookStorePermissions.Books.Resources.Name,
managementPermissionName: BookStorePermissions.Books.ManagePermissions
);
}
```
The `managementPermissionName` acts as a gate: only users who hold `ManagePermissions` will see the resource permission dialog for a book.
### Wiring Up the Dialog (MVC)
Add the required script to your page and open the dialog using `abp.ModalManager`:
```html
@section scripts
{
<abp-script src="/Pages/Books/Index.js"/>
<abp-script src="/Pages/AbpPermissionManagement/resource-permission-management-modal.js" />
}
```
```javascript
var _permissionsModal = new abp.ModalManager({
viewUrl: abp.appPath + 'AbpPermissionManagement/ResourcePermissionManagementModal',
modalClass: 'ResourcePermissionManagement'
});
function openPermissionsModal(bookId, bookName) {
_permissionsModal.open({
resourceName: 'Acme.BookStore.Books.Book',
resourceKey: bookId,
resourceDisplayName: bookName
});
}
```
> For Blazor and Angular applications, ABP provides the equivalent `ResourcePermissionManagementModal` component and `ResourcePermissionManagementComponent`. See the [Permission Management Module](https://abp.io/docs/latest/modules/permission-management) documentation for details.
## Checking Permissions in Code
The UI manages the permission assignments; the code enforces them at runtime. In your application service, use `AuthorizationService.CheckAsync` to verify that the current user holds a specific permission on a given resource instance.
All ABP entities implement `IKeyedObject`, which the framework uses to extract the resource key automatically — so you can pass the entity object directly without building the key manually:
```csharp
public virtual async Task<BookDto> GetAsync(Guid id)
{
var book = await _bookRepository.GetAsync(id);
// Throws AbpAuthorizationException if the current user has no View permission on this book
await AuthorizationService.CheckAsync(book, BookStorePermissions.Books.Resources.View);
return ObjectMapper.Map<Book, BookDto>(book);
}
public virtual async Task<BookDto> UpdateAsync(Guid id, UpdateBookDto input)
{
var book = await _bookRepository.GetAsync(id);
await AuthorizationService.CheckAsync(book, BookStorePermissions.Books.Resources.Edit);
book.Name = input.Name;
await _bookRepository.UpdateAsync(book);
return ObjectMapper.Map<Book, BookDto>(book);
}
```
If you want to check a permission without throwing an exception — for example, to conditionally show or hide a button — use `IsGrantedAsync` instead, which returns a `bool`:
```csharp
var canEdit = await AuthorizationService.IsGrantedAsync(book, BookStorePermissions.Books.Resources.Edit);
```
## Don't Forget to Clean Up
Every resource permission grant is stored as a record in the database. When a book is deleted, those records are not removed automatically — orphaned permission data accumulates over time.
Make sure to clean up resource permissions whenever a resource is deleted:
```csharp
public virtual async Task DeleteAsync(Guid id)
{
await _bookRepository.DeleteAsync(id);
// Clean up all resource permissions for this book
await _resourcePermissionManager.DeleteAsync(
resourceName: BookStorePermissions.Books.Resources.Name,
resourceKey: id.ToString()
);
}
```
## Summary
Resource-Based Authorization fills the gap between "everyone can do this" and "only specific users can do this on specific resources." In practice, most of the work comes down to two things:
- Define resource permissions and wire up the built-in UI dialog so administrators can assign access through the interface
- Call `AuthorizationService.CheckAsync` in your application services to enforce those permissions at runtime
Storing permission grants, rendering the dialog, searching for users, roles, and OAuth clients — ABP handles all of that for you.
## References
- [Resource-Based Authorization](https://abp.io/docs/latest/framework/fundamentals/authorization/resource-based-authorization)
- [Authorization](https://abp.io/docs/latest/framework/fundamentals/authorization)
- [Permission Management Module](https://abp.io/docs/latest/modules/permission-management)

BIN
docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/add-permission-dialog.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/book-list.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/cover.jpeg

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

BIN
docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/delete-permission-confirm.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

BIN
docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/resource-permission-dialog.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

BIN
docs/en/Community-Articles/2026-03-09-Resource-Based-Authorization-in-ABP-Framework/update-permission-dialog.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

252
docs/en/Community-Articles/2026-03-10-Operation-Rate-Limiting-in-ABP-Framework/POST.md

@ -0,0 +1,252 @@
# Operation Rate Limiting in ABP Framework
Almost every user-facing system eventually runs into the same problem: **some operations cannot be allowed to run without limits**.
Sometimes it's a cost issue — sending an SMS costs money, and generating a report hammers the database. Sometimes it's security — a login endpoint with no attempt limit is an open invitation for brute-force attacks. And sometimes it's a matter of fairness — your paid plan says "up to 100 data exports per month," and you need to actually enforce that.
What all these cases have in common is that the thing being limited isn't an HTTP request — it's a *business operation*, performed by a specific *who*, doing a specific *what*, against a specific *resource*.
ASP.NET Core ships with a built-in [rate limiting middleware](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit) that sits in the HTTP pipeline. It's excellent for broad API protection — throttling requests per IP to fend off bots or DDoS traffic. But it only sees HTTP requests. It can tell you how many requests came from an IP address; it cannot tell you:
- **"How many verification codes has this phone number received today?"** The moment the user switches networks, the counter resets — completely useless
- **"How many reports has this user exported today?"** Switching from mobile to desktop gives them a fresh counter
- **"How many times has someone tried to log in as `alice`?"** An attacker rotating through dozens of IPs will never hit the per-IP limit
There's another gap: some rate-limiting logic has no corresponding HTTP endpoint at all — it lives inside an application service method called by multiple endpoints, or triggered by a background job. HTTP middleware has no place to hook in.
Real-world requirements tend to look like this:
- The same phone number can receive at most 3 verification codes per hour, regardless of which device or IP the request comes from
- Each user can generate at most 2 monthly sales reports per day, because a single report query scans millions of records
- Login attempts are limited to 5 failures per username per 5 minutes, *and* 20 failures per IP per hour — two independent counters, both enforced simultaneously
- Free-tier users get 50 AI calls per month, paid users get 500 — this is a product-defined quota, not a security measure
- Your system integrates with an LLM provider (OpenAI, Azure OpenAI, etc.) where every call has a real dollar cost. Without per-user or per-tenant limits, a single user can exhaust your monthly budget overnight
The pattern is clear: the identity being throttled is a **business identity** — a user, a phone number, a resource ID — not an IP address. And the action being throttled is a **business operation**, not an HTTP request.
ABP Framework's **Operation Rate Limiting** module is built for exactly this. It lets you enforce limits directly in your application or domain layer, with full awareness of who is doing what.
Add the package to your project:
```bash
abp add-package Volo.Abp.OperationRateLimiting
```
> Operation Rate Limiting is available starting from **ABP Framework 10.3**. See the [pull request](https://github.com/abpframework/abp/pull/25024) for details.
## Defining a Policy
The model is straightforward: define a named policy in `ConfigureServices`, then call `CheckAsync` wherever you need to enforce it.
Name your policies after the business action they protect — `"SendSmsCode"`, `"GenerateReport"`, `"CallAI"`. A clear name makes the intent obvious at the call site, and avoids the mystery of something like `"policy1"`.
```csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.AddPolicy("SendSmsCode", policy =>
{
policy.WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)
.PartitionByParameter();
});
});
```
- `WithFixedWindow` sets the time window and maximum count — here, at most 1 call per minute
- `PartitionByParameter` means each distinct value you pass at call time (such as a phone number) gets its own independent counter
Then inject `IOperationRateLimitingChecker` and call `CheckAsync` at the top of the method you want to protect:
```csharp
public class SmsAppService : ApplicationService
{
private readonly IOperationRateLimitingChecker _rateLimitChecker;
public SmsAppService(IOperationRateLimitingChecker rateLimitChecker)
{
_rateLimitChecker = rateLimitChecker;
}
public async Task SendCodeAsync(string phoneNumber)
{
await _rateLimitChecker.CheckAsync("SendSmsCode", phoneNumber);
// Limit not exceeded — proceed with sending the SMS
}
}
```
`CheckAsync` checks the current usage against the limit and throws `AbpOperationRateLimitingException` (HTTP 429) if the limit is already exceeded. If the check passes, it then increments the counter and proceeds. ABP's exception pipeline catches this automatically and returns a standard error response. Put `CheckAsync` first — the rate limit check is the gate, and everything else only runs if it passes.
## Choosing a Partition Type
The partition type controls **how counters are isolated from each other** — it's the most important decision when setting up a policy, because it determines *what dimension you're counting across*.
Getting this wrong can make your rate limiting completely ineffective. Using `PartitionByClientIp` for SMS verification? An attacker just needs to switch networks. Using `PartitionByCurrentUser` for a login endpoint? There's no current user before login, so the counter has nowhere to land.
- **`PartitionByParameter`** — uses the value you explicitly pass as the partition key. This is the most flexible option. Pass a phone number, an email address, a resource ID, or any business identifier you have at hand. It's the right choice whenever you know exactly what the "who" is.
- **`PartitionByCurrentUser`** — uses the authenticated user's ID, with no value to pass. Perfect for "each user gets N per day" scenarios where user identity is all you need.
- **`PartitionByClientIp`** — uses the client's IP address. Don't rely on this alone — it's too easy to rotate. Use it as a secondary layer alongside another partition type, as in the login example below.
- **`PartitionByEmail`** and **`PartitionByPhoneNumber`** — designed for pre-authentication flows where the user isn't logged in yet. They prefer the `Parameter` value you explicitly pass, and fall back to the current user's email or phone number if none is provided.
- **`PartitionBy`** — a custom async delegate that can produce any partition key you need. When the built-in options don't fit, you're free to implement whatever logic makes sense: look up a resource's owner in the database, derive a key from the user's subscription tier, partition by tenant — anything that returns a string.
> The rule of thumb: partition by the identity of whoever's behavior you're trying to limit.
## Combining Rules in One Policy
A single rule covers most cases, but sometimes you need to enforce limits across multiple dimensions simultaneously. Login protection is the textbook example: throttling by username alone doesn't stop an attacker from targeting many accounts; throttling by IP alone doesn't stop an attacker with a botnet. You need both, at the same time.
```csharp
options.AddPolicy("Login", policy =>
{
// Rule 1: at most 5 attempts per username per 5-minute window
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromMinutes(5), maxCount: 5)
.PartitionByParameter());
// Rule 2: at most 20 attempts per IP per hour, counted independently
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 20)
.PartitionByClientIp());
});
```
The two counters are completely independent. If `alice` fails 5 times, her account is locked — but other accounts from the same IP are unaffected. If an IP accumulates 20 failures, it's blocked — but `alice` can still be targeted from other IPs until their own counters fill up.
When multiple rules are present, the module uses a two-phase approach: it checks all rules first, and only increments counters if every rule passes. This prevents a rule from consuming quota on a request that would have been rejected by another rule anyway.
## Customizing Policies from Reusable Modules
ABP modules (including your own) can ship with built-in rate limiting policies. For example, an Account module might define a `"Account.SendPasswordResetCode"` policy with conservative defaults that make sense for most applications. When you need different rules in your specific application, you have two options.
**Complete replacement with `AddPolicy`:** call `AddPolicy` with the same name and the second registration wins, replacing all rules from the module:
```csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.AddPolicy("Account.SendPasswordResetCode", policy =>
{
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromMinutes(5), maxCount: 3)
.PartitionByEmail());
});
});
```
**Partial modification with `ConfigurePolicy`:** when you only want to tweak part of a policy — change the error code, add a secondary rule, or tighten the window — use `ConfigurePolicy`. The builder starts pre-populated with the module's existing rules, so you only express what changes.
For example, keep the module's default rules but assign your own localized error code:
```csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.ConfigurePolicy("Account.SendPasswordResetCode", policy =>
{
policy.WithErrorCode("MyApp:PasswordResetLimit");
});
});
```
Or add a secondary IP-based rule on top of what the module already defined, without touching it:
```csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.ConfigurePolicy("Account.SendPasswordResetCode", policy =>
{
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 20)
.PartitionByClientIp());
});
});
```
If you want a clean slate, call `ClearRules()` first and then define entirely new rules — this gives you the same result as `AddPolicy` but makes the intent explicit:
```csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.ConfigurePolicy("Account.SendPasswordResetCode", policy =>
{
policy.ClearRules()
.WithFixedWindow(TimeSpan.FromMinutes(10), maxCount: 5)
.PartitionByEmail();
});
});
```
`ConfigurePolicy` throws if the policy name doesn't exist — which catches typos at startup rather than silently doing nothing.
The general rule: use `AddPolicy` for full replacements, `ConfigurePolicy` for surgical modifications.
## Beyond Just Checking
Not every scenario calls for throwing an exception. `IOperationRateLimitingChecker` provides three additional methods for more nuanced control.
**`IsAllowedAsync`** performs a read-only check — it returns `true` or `false` without touching any counter. The most common use case is UI pre-checking: when a user opens the "send verification code" page, check the limit first. If they've already hit it, disable the button and show a countdown immediately, rather than making them click and get an error. That's a meaningfully better experience.
```csharp
var isAllowed = await _rateLimitChecker.IsAllowedAsync("SendSmsCode", phoneNumber);
```
**`GetStatusAsync`** also reads without incrementing, but returns richer data: `RemainingCount`, `RetryAfter`, and `CurrentCount`. This is what you need to build quota displays — "You have 2 exports remaining today" or "Please try again in 47 seconds" — which are far friendlier than a raw 429.
```csharp
var status = await _rateLimitChecker.GetStatusAsync("SendSmsCode", phoneNumber);
// status.RemainingCount, status.RetryAfter, status.IsAllowed ...
```
**`ResetAsync`** clears the counter for a given policy and context. Useful in admin panels where support staff can manually unblock a user, or in test environments where you need to reset state between runs.
```csharp
await _rateLimitChecker.ResetAsync("SendSmsCode", phoneNumber);
```
## When the Limit Is Hit
When `CheckAsync` triggers, it throws `AbpOperationRateLimitingException`, which:
- Inherits from `BusinessException` and maps to HTTP **429 Too Many Requests**
- Is handled automatically by ABP's exception pipeline
- Carries useful metadata: `RetryAfterSeconds`, `RemainingCount`, `MaxCount`, `CurrentCount`
By default, the error code sent to the client is a generic one from the module. If you want each operation to produce its own localized message — "Too many verification code requests, please wait before trying again" instead of a generic error — assign a custom error code to the policy:
```csharp
options.AddPolicy("SendSmsCode", policy =>
{
policy.WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)
.PartitionByParameter()
.WithErrorCode("App:SmsCodeLimit");
});
```
> For details on mapping error codes to localized messages, see [Exception Handling](https://abp.io/docs/latest/framework/fundamentals/exception-handling) in the ABP docs.
## Turning It Off in Development
Rate limiting and local development don't mix well. When you're iterating quickly and calling the same endpoint a dozen times to test something, getting blocked by a 429 every few seconds is genuinely painful. Disable the module in your development environment:
```csharp
public override void ConfigureServices(ServiceConfigurationContext context)
{
var hostEnvironment = context.Services.GetHostingEnvironment();
Configure<AbpOperationRateLimitingOptions>(options =>
{
if (hostEnvironment.IsDevelopment())
{
options.IsEnabled = false;
}
});
}
```
## Summary
ABP's Operation Rate Limiting fills the gap that ASP.NET Core's HTTP middleware can't: rate limiting with real awareness of *who* is doing *what*. Define a named policy, pick a time window, a max count, and a partition type. Call `CheckAsync` wherever you need it. Counter storage, distributed locking, and exception handling are all taken care of.
## References
- [Operation Rate Limiting](https://abp.io/docs/latest/framework/infrastructure/operation-rate-limiting)
- [ASP.NET Core Rate Limiting Middleware](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit)
- [Exception Handling](https://abp.io/docs/latest/framework/fundamentals/exception-handling)

BIN
docs/en/Community-Articles/2026-03-10-Operation-Rate-Limiting-in-ABP-Framework/cover.jpeg

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

113
docs/en/Community-Articles/2026-03-10-Tutorial-Validator/article.md

@ -0,0 +1,113 @@
# Automatically Validate Your Documentation: How We Built a Tutorial Validator
Writing a tutorial is difficult. Keeping technical documentation accurate over time is even harder.
If you maintain developer documentation, you probably know the problem: a tutorial that worked a few months ago can silently break after a framework update, dependency change, or a small missing line in a code snippet.
New developers follow the guide, encounter an error, and quickly lose trust in the documentation.
To solve this problem, we built the tutorial validator — an open-source AI-powered tutorial validator that automatically verifies whether a software tutorial actually works from start to finish.
Instead of manually reviewing documentation, the tutorial validator behaves like a real developer following your guide step by step.
It reads instructions, runs commands, writes files, executes the application, and verifies expected results.
We initially created it to automatically validate ABP Framework tutorials, then released it as an open-source tool so anyone can use it to test their own documentation.
![the tutorial validator Orchestrator](docs/images/image.png)
## The Problem: Broken Tutorials in Technical Documentation
Many documentation issues are difficult to catch during normal reviews.
Common problems include:
- A command assumes a file already exists
- A code snippet misses a namespace or import
- A tutorial step relies on hidden context
- An endpoint is expected to respond but fails
- A dependency version changed and breaks the project
Traditional proofreading tools only check grammar or wording.
**The tutorial validator focuses on execution correctness.**
It treats tutorials like testable workflows, ensuring that every step works exactly as written.
## How the Tutorial Validator Works?
the tutorial validator validates tutorials using a three-stage pipeline:
1. **Analyst**: Scrapes tutorial pages and converts instructions into a structured test plan
2. **Executor**: Follows the plan step by step in a clean environment
3. **Reporter**: Produces a clear result summary and optional notifications
![the tutorial validator Analyst](docs/images/image-1.png)
It identifies commands, code edits, HTTP requests, and expected outcomes.
The key idea is simple: if a developer would need to do it, the validator does it too.
That includes running terminal commands, editing files, checking HTTP responses, and validating build outcomes.
![the tutorial validator Executor](docs/images/image-2.png)
## Why Automated Tutorial Validation Matters?
The tutorial validator is designed for practical documentation quality, not just technical experimentation.
- **Catches real-world breakages early** before readers report them
- **Creates repeatable validation** instead of one-off manual checks
- **Works well in teams** through report outputs, logs, and CI-friendly behavior
- **Supports different strictness levels** with developer personas (`junior`, `mid`, `senior`)
For example, `junior` and `mid` personas are great for spotting unclear documentation, while `senior` helps identify issues an experienced developer could work around.
## Built for ABP, Open for Everyone
Although TutorialValidator was originally built to validate **ABP Framework tutorials**, it works with **any publicly accessible software tutorial**.
It supports validating any publicly accessible software tutorial and can run in:
- **Docker mode** for clean, isolated execution (recommended)
- **Local mode** for faster feedback when your environment is already prepared
It also supports multiple AI providers, including OpenAI, Azure OpenAI, and OpenAI-compatible endpoints.
## Open Source and Easily Extensible
The tutorial validator is designed with a modular architecture.
The project consists of multiple focused components:
- **Core** – shared models and contracts
- **Analyst** – tutorial scraping and step extraction
- **Executor** – step-by-step execution engine
- **Orchestrator** – workflow coordination
- **Reporter** – notifications and result summaries
This architecture makes it easy to extend the validator with:
- new step types
- additional AI providers
- custom reporting integrations
This architecture keeps the project easy to understand and extend. Teams can add new step types, plugins, or reporting channels based on their own workflow.
## Final Thoughts
Documentation is a critical part of the product experience.
When tutorials break, developer trust breaks too.
TutorialValidator helps teams move from:
> We believe this tutorial works 🙄
to
> We verified this tutorial works ✅
If your team maintains **technical tutorials, developer guides, or framework documentation**, automated tutorial validation can provide a powerful safety net.
Documentation is part of the product experience. When tutorials fail, trust fails.
If your team maintains technical tutorials, this project can give you a practical safety net and a repeatable quality process.
---
You can find the source-code of the tutorial validator at this repo 👉 https://github.com/abpframework/tutorial-validator
We would love to hear your feedback, ideas and waiting PRs to improve this application.

BIN
docs/en/Community-Articles/2026-03-10-Tutorial-Validator/docs/images/image-1.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

BIN
docs/en/Community-Articles/2026-03-10-Tutorial-Validator/docs/images/image-2.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
docs/en/Community-Articles/2026-03-10-Tutorial-Validator/docs/images/image.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

185
docs/en/Community-Articles/2026-03-12-OpenIddict-private-key-jwt/POST.md

@ -0,0 +1,185 @@
# Secure Client Authentication with private_key_jwt in ABP 10.3
If you've built a confidential client with ABP's OpenIddict module, you know the drill: create an application in the management UI, set a `client_id`, generate a `client_secret`, and paste that secret into your client's `appsettings.json` or environment variables. It works. It's familiar. And for a lot of projects, it's perfectly fine.
But `client_secret` is a **shared secret** — and shared secrets carry an uncomfortable truth: the same value exists in two places at once. The authorization server stores a hash of it in the database, and your client stores the raw value in configuration. That means two potential leak points. Worse, the secret has no inherent identity. Anyone who obtains the string can impersonate your client and the server has no way to tell the difference.
For many teams, this tradeoff is acceptable. But certain scenarios make it hard to ignore:
- **Microservice-to-microservice calls**: A backend mesh of a dozen services, each with its own `client_secret` scattered across deployment configs and CI/CD pipelines. Rotating them across environments without missing one becomes a coordination problem.
- **Multi-tenant SaaS platforms**: Every tenant's client application deserves truly isolated credentials. With shared secrets, the database holds hashed copies for all tenants — a breach of that table is a breach of everyone's credentials.
- **Financial-grade API (FAPI) compliance**: Standards like [FAPI 2.0](https://openid.net/specs/fapi-2_0-security-profile.html) explicitly require asymmetric client authentication. `client_secret` doesn't make the cut.
- **Zero-trust architectures**: In a zero-trust model, identity must be cryptographically provable, not based on a string that can be copied and pasted.
The underlying problem is that a shared secret is just a password. It can be stolen, replicated, and used without leaving a trace. The fix has existed in cryptography for decades: **asymmetric keys**.
With asymmetric key authentication, the client generates a key pair. The public key is registered with the authorization server. The private key never leaves the client. Each time the client needs a token, it signs a short-lived JWT — called a _client assertion_ — with the private key. The server verifies the signature using the registered public key. There is no secret on the server side that could be used to forge a request, because the private key is never transmitted or stored remotely.
This is exactly what the **`private_key_jwt`** client authentication method, defined in [OpenID Connect Core](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication), provides. ABP's OpenIddict module now supports it end-to-end: you register a **JSON Web Key Set (JWKS)** containing your public key through the application management UI (ABP Commercial), and your client authenticates using the corresponding private key. The key generation tooling (`abp generate-jwks`) ships as part of the open-source ABP CLI.
> This feature is available starting from **ABP Framework 10.3**.
## How It Works
The flow is straightforward:
1. The client holds an RSA key pair — **private key** (kept locally) and **public key** (registered on the authorization server as a JWKS).
2. On each token request, the client uses the private key to sign a JWT with a short expiry and a unique `jti` claim.
3. The authorization server verifies the signature against the registered public key and issues a token if it checks out.
The private key never leaves the client. Even if someone obtains the authorization server's database, there's nothing there that can be used to generate a valid client assertion.
## Generating a Key Pair
ABP CLI includes a `generate-jwks` command that creates an RSA key pair in the right formats:
```bash
abp generate-jwks
```
This produces two files in the current directory:
- `jwks.json` — the public key in JWKS format, to be uploaded to the server
- `jwks-private.pem` — the private key in PKCS#8 PEM format, to be kept on the client
You can customize the output directory, key size, and signing algorithm:
```bash
abp generate-jwks --alg RS512 --key-size 4096 -o ./keys -f myapp
```
> Supported algorithms: `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`. The default is `RS256` with a 2048-bit key.
The command also prints the contents of `jwks.json` to the console so you can copy it directly.
## Registering the JWKS in the Management UI
Open **OpenIddict → Applications** in the ABP admin panel and create or edit a confidential application (Client Type: `Confidential`).
In the **Client authentication method** section, you'll find the new **JSON Web Key Set** field.
![](./create-edit-ui.png)
Paste the contents of `jwks.json` into the **JSON Web Key Set** field:
```json
{
"keys": [
{
"kty": "RSA",
"use": "sig",
"kid": "6444...",
"alg": "RS256",
"n": "tx...",
"e": "AQAB"
}
]
}
```
Save the application. It's now configured for `private_key_jwt` authentication. You can set either `client_secret` or a JWKS, or both — ABP enforces that a confidential application always has at least one credential.
## Requesting a Token with the Private Key
On the client side, each token request requires building a _client assertion_ JWT signed with the private key. Here's a complete `client_credentials` example:
```csharp
// Discover the authorization server endpoints (including the issuer URI).
var client = new HttpClient();
var configuration = await client.GetDiscoveryDocumentAsync("https://your-auth-server/");
// Load the private key generated by `abp generate-jwks`.
using var rsaKey = RSA.Create();
rsaKey.ImportFromPem(await File.ReadAllTextAsync("jwks-private.pem"));
// Read the kid from jwks.json so it stays in sync with the server-registered public key.
string? signingKid = null;
if (File.Exists("jwks.json"))
{
using var jwksDoc = JsonDocument.Parse(await File.ReadAllTextAsync("jwks.json"));
if (jwksDoc.RootElement.TryGetProperty("keys", out var keysElem) &&
keysElem.GetArrayLength() > 0 &&
keysElem[0].TryGetProperty("kid", out var kidElem))
{
signingKid = kidElem.GetString();
}
}
var signingKey = new RsaSecurityKey(rsaKey) { KeyId = signingKid };
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256);
// Build the client assertion JWT.
var now = DateTime.UtcNow;
var jwtHandler = new JsonWebTokenHandler();
var clientAssertionToken = jwtHandler.CreateToken(new SecurityTokenDescriptor
{
// OpenIddict requires typ = "client-authentication+jwt" for client assertion JWTs.
TokenType = "client-authentication+jwt",
Issuer = "MyClientId",
// aud must equal the authorization server's issuer URI from the discovery document,
// not the token endpoint URL.
Audience = configuration.Issuer,
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "MyClientId"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
}),
IssuedAt = now,
NotBefore = now,
Expires = now.AddMinutes(5),
SigningCredentials = signingCredentials,
});
// Request a token using the client_credentials flow.
var tokenResponse = await client.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = configuration.TokenEndpoint,
ClientId = "MyClientId",
ClientCredentialStyle = ClientCredentialStyle.PostBody,
ClientAssertion = new ClientAssertion
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = clientAssertionToken,
},
Scope = "MyAPI",
});
```
A few things worth paying attention to:
- **`TokenType`** must be `"client-authentication+jwt"`. OpenIddict rejects client assertion JWTs that don't carry this header.
- **`Audience`** must match the authorization server's issuer URI exactly — use `configuration.Issuer` from the discovery document, not the token endpoint URL.
- **`Jti`** must be unique per request to prevent replay attacks.
- Keep **`Expires`** short (five minutes or less). A client assertion is a one-time proof of identity, not a long-lived credential.
This example uses [IdentityModel](https://github.com/IdentityModel/IdentityModel) for the token request helpers and [Microsoft.IdentityModel.JsonWebTokens](https://www.nuget.org/packages/Microsoft.IdentityModel.JsonWebTokens) for JWT creation.
## Key Rotation Without Downtime
One of the practical advantages of JWKS is that it can hold multiple public keys simultaneously. This makes **zero-downtime key rotation** straightforward:
1. Run `abp generate-jwks` to produce a new key pair.
2. Append the new public key to the `keys` array in your existing `jwks.json` and update the JWKS in the management UI.
3. Switch the client to sign assertions with the new private key.
4. Once the transition is complete, remove the old public key from the JWKS.
During the transition window, both the old and new public keys are registered on the server, so any in-flight requests signed with either key will still validate correctly.
## Summary
To use `private_key_jwt` authentication in an ABP Pro application:
1. Run `abp generate-jwks` to generate an RSA key pair.
2. Paste the `jwks.json` contents into the **JSON Web Key Set** field in the OpenIddict application management UI.
3. On the client side, sign a short-lived _client assertion_ JWT with the private key — making sure to set the correct `typ`, `aud` (from the discovery document), and a unique `jti` — then use it to request a token.
ABP handles public key storage and validation automatically. OpenIddict handles the signature verification on the token endpoint. As a developer, you only need to keep the private key file secure — there's no shared secret to synchronize between client and server.
## References
- [OpenID Connect Core — Client Authentication](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication)
- [RFC 7523 — JWT Profile for Client Authentication](https://datatracker.ietf.org/doc/html/rfc7523)
- [ABP OpenIddict Module Documentation](https://abp.io/docs/latest/modules/openiddict)
- [ABP CLI Documentation](https://abp.io/docs/latest/cli)
- [OpenIddict Documentation](https://documentation.openiddict.com/)

BIN
docs/en/Community-Articles/2026-03-12-OpenIddict-private-key-jwt/cover.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

BIN
docs/en/Community-Articles/2026-03-12-OpenIddict-private-key-jwt/create-edit-ui.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

151
docs/en/Community-Articles/2026-03-17-OpenAI-Compatible-Endpoints/POST.md

@ -0,0 +1,151 @@
# One Endpoint, Many AI Clients: Turning ABP Workspaces into OpenAI-Compatible Models
ABP's AI Management module already makes it easy to define and manage AI workspaces (provider, model, API key/base URL, system prompt, permissions, MCP tools, RAG settings, and more). With **ABP v10.2**, there is a major addition: you can now expose those workspaces through **OpenAI-compatible endpoints** under `/v1`.
That changes the integration story in a practical way. Instead of wiring every external tool directly to a provider, you can point those tools to ABP and keep runtime decisions centralized in one place.
In this post, we will walk through a practical setup with **AnythingLLM** and show why this pattern is useful in real projects.
Before we get into the details, here's a quick look at the full flow in action:
## See It in Action: AnythingLLM + ABP
The demo below shows the full flow: connecting an OpenAI-compatible client to ABP, selecting a workspace-backed model, and sending a successful chat request through `/v1`.
![ABP AI Management OpenAI-compatible endpoints demo](./openai-compatible-endpoints-demo.gif)
## Why This Is a Big Deal
Many teams end up with AI configuration spread across multiple clients and services. Updating providers, rotating keys, or changing model behavior can become operationally messy.
With ABP in front of your AI traffic:
- Clients keep speaking the familiar OpenAI contract.
- ABP resolves the requested `model` to a workspace.
- The workspace decides which provider/model settings are actually used.
This gives you a clean split: standardized client integration outside, governed AI configuration inside.
## Key Concept: Workspace = Model
OpenAI-compatible clients send a `model` value.
In ABP AI Management, that `model` maps to a **workspace name**.
**For example:**
- Workspace name: `SupportAgent`
- Client request model: `SupportAgent`
When the client calls `/v1/chat/completions` with `"model": "SupportAgent"`, ABP routes the request to that workspace and applies that workspace's provider (OpenAI, Ollama etc.) and model configuration.
This is the main mental model to keep in mind while integrating any OpenAI-compatible tool with ABP.
## Endpoints Exposed by ABP v10.2
The AI Management module exposes OpenAI-compatible REST endpoints at `/v1`.
| Endpoint | Method | Description |
| ---------------------------- | ------ | ---------------------------------------------- |
| `/v1/chat/completions` | POST | Chat completions (streaming and non-streaming) |
| `/v1/completions` | POST | Legacy text completions |
| `/v1/models` | GET | List available models (workspaces) |
| `/v1/models/{modelId}` | GET | Get a single model (workspace) |
| `/v1/embeddings` | POST | Generate embeddings |
| `/v1/files` | GET | List files |
| `/v1/files` | POST | Upload a file |
| `/v1/files/{fileId}` | GET | Get file metadata |
| `/v1/files/{fileId}` | DELETE | Delete a file |
| `/v1/files/{fileId}/content` | GET | Download file content |
All endpoints require `Authorization: Bearer <token>`.
## Quick Setup with AnythingLLM
Before configuration, ensure:
1. AI Management is installed and running in your ABP app.
2. At least one workspace is created and **active**.
3. You have a valid Bearer token for your ABP application.
### 1) Get an access token
Use any valid token accepted by your app. In a demo-style setup, token retrieval can look like this:
```bash
curl -X POST http://localhost:44337/connect/token \
-d "grant_type=password&username=admin&password=1q2w3E*&client_id=DemoApp_API&client_secret=1q2w3e*&scope=DemoApp"
```
Use the returned `access_token` as the API key value in your OpenAI-compatible client.
### 2) Configure AnythingLLM as Generic OpenAI
In **AnythingLLM -> Settings -> LLM Preference**, select **Generic OpenAI** and set:
| Setting | Value |
| -------------------- | --------------------------- |
| Base URL | `http://localhost:44337/v1` |
| API Key | `<access_token>` |
| Chat Model Selection | Select an active workspace |
In most OpenAI-compatible UIs, the app adds `Bearer` automatically, so the API key field should contain only the raw token string.
### 3) Optional: configure embeddings
If you want RAG flows through ABP, go to **Settings -> Embedding Preference** and use the same Base URL/API key values.
Then select a workspace that has embedder settings configured.
## Validate the Flow
### List models (workspaces)
```bash
curl http://localhost:44337/v1/models \
-H "Authorization: Bearer <your-token>"
```
### Chat completion
```bash
curl -X POST http://localhost:44337/v1/chat/completions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json" \
-d '{
"model": "MyWorkspace",
"messages": [
{ "role": "user", "content": "Hello from ABP OpenAI-compatible endpoint!" }
]
}'
```
### Optional SDK check (Python)
```python
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:44337/v1",
api_key="<your-token>"
)
response = client.chat.completions.create(
model="MyWorkspace",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
```
## Where This Fits in Real Projects
This approach is a strong fit when you want to:
- Keep ABP as the central control plane for AI workspaces.
- Let client tools integrate through a standard OpenAI contract.
- Switch providers or model settings without rewriting client-side integration.
If your team uses multiple AI clients, this pattern keeps integration simple while preserving control where it matters.
## Learn More
- [ABP AI Management Documentation](https://abp.io/docs/10.2/modules/ai-management)

BIN
docs/en/Community-Articles/2026-03-17-OpenAI-Compatible-Endpoints/cover-image.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 324 KiB

BIN
docs/en/Community-Articles/2026-03-17-OpenAI-Compatible-Endpoints/openai-compatible-endpoints-demo.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 MiB

167
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/POST.md

@ -0,0 +1,167 @@
# Shared User Accounts in ABP Multi-Tenancy
Multi-tenancy is built on **isolation** — isolated data, isolated permissions, isolated users. ABP's default behavior has always followed this assumption: one user belongs to exactly one tenant. Clean, simple, no ambiguity. For most SaaS applications, that's exactly what you want. (The new `TenantUserSharingStrategy` enum formally names this default behavior `Isolated`.)
But isolation is **the system's** concern, not **the user's**. In practice, people's work doesn't always line up neatly with tenant boundaries.
Think about a financial consultant who works with three different companies — each one a tenant in your system. Under the Isolated model, she needs three separate accounts, three passwords. Forgot which password goes with which company? Good luck. Worse, the system sees three unrelated people — there's nothing linking those accounts to the same human being.
This comes up more often than you'd think:
- In a **corporate group**, an IT admin manages multiple subsidiaries, each running as its own tenant. Every day means logging out, logging back in with different credentials, over and over
- A **SaaS platform's ops team** needs to hop into different customer tenants to debug issues. Each time they create a throwaway account, then delete it — or just share one account and lose all audit trail
- Some users resort to email aliases (`alice+company1@example.com`) to work around uniqueness constraints — that's not a solution, that's a hack
The common thread here: the user's **identity** is global, but their **working context** is per-tenant. The problem isn't a technical limitation — it's that the Isolated assumption ("one user, one tenant") simply doesn't hold in these scenarios.
What's needed is not "one account per tenant" but "one account, multiple tenants."
ABP's **Shared User Accounts** (`TenantUserSharingStrategy.Shared`) does exactly this. It makes user identity global and turns tenants into workspaces that a user can join and switch between — similar to how one person can belong to multiple workspaces in Slack.
> This is a **commercial** feature, available starting from **ABP 10.2**, provided by the Account.Pro and Identity.Pro modules.
## Enabling the Shared Strategy
A single configuration is all it takes:
```csharp
Configure<AbpMultiTenancyOptions>(options =>
{
options.IsEnabled = true;
options.UserSharingStrategy = TenantUserSharingStrategy.Shared;
});
```
The most important behavior change after switching to Shared: **username and email uniqueness become global** instead of per-tenant. This follows naturally — if the same account needs to be recognized across tenants, its identifiers must be unique across the entire system.
Security-related settings (2FA, account lockout, password policies, captcha, etc.) are also managed at the **Host** level. This makes sense too: if user identity is global, the security rules around it should be global as well.
## One Account, Multiple Tenants
With the Shared strategy enabled, the day-to-day user experience changes fundamentally.
When a user is associated with only one tenant, the system recognizes it automatically and signs them in directly — the user doesn't even notice that tenants exist. When the user belongs to multiple tenants, the login flow presents a tenant selection screen after credentials are verified:
![tenant-selection](./tenant-selection.png)
After signing into a tenant, a tenant switcher appears in the user menu — click it anytime to jump to another tenant without signing out. ABP re-issues the authentication ticket (with the new `TenantId` in the claims) on each switch, so the permission system is fully independent per tenant.
![switch-tenant](./switch-tenant.png)
Users can also leave a tenant. Leaving doesn't delete the association record — it marks it as inactive. This preserves foreign key relationships with other entities. If the user is invited back later, the association is simply reactivated instead of recreated.
Back to our earlier scenario: the financial consultant now has one account, one password. She picks which company to work in at login, switches between them during the day. The system knows it's the same person, and the audit log can trace her actions across every tenant.
## Invitations
Users don't just appear in a tenant — someone has to invite them. This is the core operation from the administrator's perspective.
A tenant admin opens the invitation dialog, enters one or more email addresses (batch invitations are supported), and can pre-assign roles — so the user gets the right permissions the moment they join, no extra setup needed:
![invite-user](./invite-user.png)
The invited person receives an email with a link. What happens next depends on whether they already have an account.
If they **already have an account**, they see a confirmation page and can join the tenant with a single click:
![exist-user-accept](./exist-user-accept.png)
If they **don't have an account yet**, the link takes them to a registration form. Once they register, they're automatically added to the tenant:
![new-user-accept](./new-user-accept.png)
Admins can also manage pending invitations at any time — resend emails or revoke invitations.
> The invitation feature is also available under the Isolated strategy, but invited users can only join a single tenant.
## Setting Up a New Tenant
There's a notable shift in how new tenants are bootstrapped.
Under the Isolated model, creating a tenant typically seeds an `admin` user automatically. With Shared, this no longer happens — because users are global, and it doesn't make sense to create one out of thin air for a specific tenant.
Instead, you create the tenant first, then invite someone in and grant them the admin role.
![invite-admin-user-to-join-tenant](./invite-admin-user-to-join-tenant.png)
![invite-admin-user-to-join-tenant-modal](./invite-admin-user-to-join-tenant-modal.png)
This is a natural fit — the admin is just a global user who happens to hold the admin role in this particular tenant.
## Where Do Newly Registered Users Go?
Under the Shared strategy, self-registration runs into an interesting problem: the system doesn't know which tenant the user wants to join. Without being signed in, tenant context is usually determined by subdomain or a tenant switcher on the login page — but for a brand-new user, those signals might not exist at all.
So ABP's approach is: **don't establish any tenant association at registration time**. A newly registered user doesn't belong to any tenant, and doesn't belong to the Host either — this is an entirely new state. ABP still lets these users sign in, change their password, and manage their account, but they can't access any permission-protected features within a tenant.
`AbpIdentityPendingTenantUserOptions.Strategy` controls what happens in this "pending" state.
**CreateTenant** — automatically creates a tenant for the new user. This fits the "sign up and get your own workspace" pattern, like how Slack or Notion handles registration: you register, the system spins up a workspace for you.
```csharp
Configure<AbpIdentityPendingTenantUserOptions>(options =>
{
options.Strategy = AbpIdentityPendingTenantUserStrategy.CreateTenant;
});
```
![new-user-join-strategy-create-tenant](./new-user-join-strategy-create-tenant.png)
**Inform** (the default) — shows a message telling the user to contact an administrator to join a tenant. This is the right choice for invite-only platforms where users must be brought in by an existing tenant admin.
```csharp
Configure<AbpIdentityPendingTenantUserOptions>(options =>
{
options.Strategy = AbpIdentityPendingTenantUserStrategy.Inform;
});
```
![new-user-join-strategy-inform](./new-user-join-strategy-inform.png)
There's also a **Redirect** strategy that sends the user to a custom URL for more complex flows.
> See the [official documentation](https://abp.io/docs/latest/modules/account/shared-user-accounts) for full configuration details.
## Database Considerations
The Shared strategy introduces some mechanisms and constraints at the database level that are worth understanding.
### Global Uniqueness: Enforced in Code, Not by Database Indexes
Username and email uniqueness checks must span all tenants. ABP disables the tenant filter (`TenantFilter.Disable()`) during validation and searches globally for conflicts.
A notable design choice here: **global uniqueness is enforced at the application level, not through database unique indexes**. The reason is practical — in a database-per-tenant setup, users live in separate physical databases, so a cross-database unique index simply isn't possible. Even in a shared database, soft-delete complicates unique indexes (you'd need a composite index on "username + deletion time"). So ABP handles this in application code instead.
To keep things safe under concurrency — say two tenant admins invite the same email address at the same time — ABP uses a **distributed lock** to serialize uniqueness validation. This means your production environment needs a distributed lock provider configured (such as Redis).
The uniqueness check goes beyond just "no duplicate usernames." ABP also checks for **cross-field conflicts**: a user's username can't match another user's email, and vice versa. This prevents identity confusion in edge cases.
### Tenants with Separate Databases
If some of your tenants use their own database (database-per-tenant), the Shared strategy requires extra attention.
The login flow and tenant selection happen on the **Host side**. This means the Host database's `AbpUsers` table must contain records for all users — even those originally created in a tenant's separate database. ABP's approach is replication: it saves the primary user record in the Host context and creates a copy in the tenant context. In a shared-database setup, both records live in the same table; in a database-per-tenant setup, they live in different physical databases. Updates and deletes are kept in sync automatically.
If your application uses social login or passkeys, the `AbpUserLogins` and `AbpUserPasskeys` tables also need to be synced in the Host database.
### Migrating from the Isolated Strategy
If you're moving an existing multi-tenant application from Isolated to Shared, ABP automatically runs a global uniqueness check when you switch the strategy and reports any conflicts.
The most common conflict: the same email address registered as separate users in different tenants. You'll need to resolve these first — merge the accounts or change one side's email — before the Shared strategy can be enabled.
## Summary
ABP's Shared User Accounts addresses a real-world need in multi-tenant systems: one person working across multiple tenants.
- One configuration switch to `TenantUserSharingStrategy.Shared`
- User experience: pick a tenant at login, switch between tenants anytime, one password for everything
- Admin experience: invite users by email, pre-assign roles on invitation
- Database notes: configure a distributed lock provider for production; tenants with separate databases need user records replicated in the Host database
ABP takes care of global uniqueness validation, tenant association management, and login flow adaptation under the hood.
## References
- [Shared User Accounts](https://abp.io/docs/latest/modules/account/shared-user-accounts)
- [ABP Multi-Tenancy](https://abp.io/docs/latest/framework/architecture/multi-tenancy)

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/cover.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/exist-user-accept.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/invite-admin-user-to-join-tenant-modal.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/invite-admin-user-to-join-tenant.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/invite-user.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/new-user-accept.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/new-user-join-strategy-create-tenant.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/new-user-join-strategy-inform.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/switch-tenant.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

BIN
docs/en/Community-Articles/2026-03-17-Shared-User-Accounts-in-ABP/tenant-selection.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

94
docs/en/cli/index.md

@ -75,6 +75,7 @@ Here is the list of all available commands before explaining their details:
* **[`install-old-cli`](../cli#install-old-cli)**: Installs old ABP CLI.
* **[`mcp-studio`](../cli#mcp-studio)**: Starts ABP Studio MCP bridge for AI tools (requires ABP Studio running).
* **[`generate-razor-page`](../cli#generate-razor-page)**: Generates a page class that you can use it in the ASP NET Core pipeline to return an HTML page.
* **[`generate-jwks`](../cli#generate-jwks)**: Generates an RSA key pair (JWKS public key + PEM private key) for OpenIddict `private_key_jwt` client authentication.
### help
@ -1127,6 +1128,99 @@ app.Use(async (httpContext, next) =>
* ```--version``` or ```-v```: Specifies the version for ABP CLI to be installed.
### generate-jwks
Generates an RSA key pair for use with OpenIddict `private_key_jwt` client authentication.
The command produces two files:
| File | Description |
|---|---|
| `<prefix>.json` | JWKS (JSON Web Key Set) containing the **public key**. Paste this into the **JSON Web Key Set** field of your OpenIddict application in the ABP management UI. |
| `<prefix>-private.pem` | PKCS#8 PEM **private key**. Store this securely in your client application and use it to sign JWT client assertions. |
> **Security notice:** Never commit the private key file to source control. Add it to `.gitignore`. Only the JWKS (public key) needs to be shared with the authorization server.
Usage:
```bash
abp generate-jwks [options]
```
#### Options
* `--output` or `-o`: Output directory. Defaults to the current directory.
* `--key-size` or `-s`: RSA key size in bits. Supported values: `2048` (default), `4096`.
* `--alg`: Signing algorithm. Supported values: `RS256` (default), `RS384`, `RS512`, `PS256`, `PS384`, `PS512`.
* `--kid`: Custom Key ID. Auto-generated if not specified.
* `--file` or `-f`: Output file name prefix. Defaults to `jwks`. Generates `<prefix>.json` and `<prefix>-private.pem`.
#### Examples
```bash
# Generate with defaults (2048-bit RS256, current directory)
abp generate-jwks
# Generate with RS512 and 4096-bit key
abp generate-jwks --alg RS512 --key-size 4096
# Output to a specific directory with a custom file prefix
abp generate-jwks -o ./keys -f myapp
```
#### Workflow
1. Run `abp generate-jwks` to generate the key pair.
2. Open the ABP OpenIddict application management UI, select your **Confidential** application, choose **JWKS (private_key_jwt)** as the authentication method, and paste the contents of `jwks.json` into the **JSON Web Key Set** field.
3. In your client application, load the private key from the PEM file and sign JWT client assertions:
```csharp
// Load private key from PEM file
using var rsa = RSA.Create();
rsa.ImportFromPem(await File.ReadAllTextAsync("jwks-private.pem"));
// The kid must match the "kid" field in the JWKS registered on the server
var signingKey = new RsaSecurityKey(rsa) { KeyId = "<kid-from-jwks.json>" };
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256);
var now = DateTime.UtcNow;
var jwtHandler = new JsonWebTokenHandler();
var clientAssertion = jwtHandler.CreateToken(new SecurityTokenDescriptor
{
// OpenIddict requires typ = "client-authentication+jwt"
TokenType = "client-authentication+jwt",
// iss and sub must both equal the client_id
Issuer = "<your-client-id>",
Audience = "<authorization-server-issuer-uri>",
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "<your-client-id>"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
}),
IssuedAt = now,
NotBefore = now,
Expires = now.AddMinutes(5),
SigningCredentials = signingCredentials,
});
// Use the assertion in the token request
var tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = "<token-endpoint>",
ClientId = "<your-client-id>",
ClientCredentialStyle = ClientCredentialStyle.PostBody,
ClientAssertion = new ClientAssertion
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = clientAssertion,
},
Scope = "<requested-scopes>",
});
```
## See Also
* [Examples for the new command](./new-command-samples.md)

168
docs/en/contribution/angular-ui.md

@ -7,58 +7,168 @@
# Contribution Guide for the Angular UI
This guide explains how to set up the ABP Angular UI workspace, run the demo app, and prepare your environment to contribute UI changes. It assumes that you are already familiar with basic Angular and .NET development.
> Before sending a pull request for Angular UI changes, please also read the main [Contribution Guide](index.md).
## Pre-requirements
- Dotnet core SDK https://dotnet.microsoft.com/en-us/download
- Nodejs LTS https://nodejs.org/en/
- Docker https://docs.docker.com/engine/install
- Angular CLI. https://angular.dev/tools/cli
- Abp CLI https://docs.abp.io/en/abp/latest/cli
- A code editor
Make sure you have the following tools installed:
- [.NET SDK](https://dotnet.microsoft.com/en-us/download)
- [Node.js LTS](https://nodejs.org/en/) (recommended: use the version supported by the Angular CLI used in this repository)
- [Docker Engine](https://docs.docker.com/engine/install/) (required if you use the sample SQL Server and Redis containers)
- [Angular CLI](https://angular.dev/tools/cli)
- [ABP CLI](https://docs.abp.io/en/abp/latest/cli)
- A code editor (for example, Visual Studio Code or Visual Studio)
Note: This article prepare Windows OS. You may change the path type of your OS.
> This article uses Windows-style paths in examples. On Unix-like systems, replace backslashes (`\`) with forward slashes (`/`).
Examples:
* Windows: `templates\app\aspnet-core\src\MyCompanyName.MyProjectName.DbMigrator\appsettings.json`
* Unix: `templates/app/aspnet-core/src/MyCompanyName.MyProjectName.DbMigrator/appsettings.json`
- Windows: `templates\app\aspnet-core\src\MyCompanyName.MyProjectName.DbMigrator\appsettings.json`
- Unix: `templates/app/aspnet-core/src/MyCompanyName.MyProjectName.DbMigrator/appsettings.json`
## Sample docker commands
## Sample Docker Commands
You need to install SQL Server and Redis. You can install these programs without docker, but my example uses docker containers. Your computer should have Docker Engine. Then open the terminal and execute the commands one by one.
For the SQL Server
You need SQL Server and Redis. You can install these programs without Docker, but the examples below use Docker containers. Your computer should have Docker Engine running. Then open a terminal and execute the commands.
```cmd
docker run -v sqlvolume:/var/opt/mssql -e 'ACCEPT_EULA=Y' -e "SA_PASSWORD=yourpassword" -p 1433:1433 -d mcr.microsoft.com/mssql/server:2019-CU3-ubuntu-18.04
### SQL Server
```bash
docker run -v sqlvolume:/var/opt/mssql \
-e 'ACCEPT_EULA=Y' \
-e 'SA_PASSWORD=YourStrong!Passw0rd' \
-p 1433:1433 \
-d mcr.microsoft.com/mssql/server:2019-CU3-ubuntu-18.04
```
For the Redis
- Replace `YourStrong!Passw0rd` with a strong password that satisfies SQL Server password requirements.
- The `sqlvolume` named volume is used to persist database files.
### Redis
```cmd
docker run -p 6379:6379 -d redis
```bash
docker run -p 6379:6379 -d redis:latest
```
Then we are ready to download and execute the code.
After running the commands, you can use `docker ps` to verify that both containers are running.
Once the containers are ready, you can download the ABP source code and run the apps.
## Folder Structure
The app has a backend written in .net core (c#) and an angular app. It would help if you ran both of them.
The sample application has:
- A backend built with ASP.NET Core (C#).
- An Angular workspace managed by Nx.
You will run both the backend and the Angular dev app during development.
## Running the Backend App
The backend root path is `templates\app\aspnet-core`.
### 1. Configure the Connection Strings
## Running Backend App
If you are using the Dockerized SQL Server, update the connection strings to point to your Docker container. The configuration file is:
The path of the Backend app is “templates\app\aspnet-core.” If you want to work with dockerized SQL Server, you should change connection strings for running with docker. The path of the connection string is
`templates\app\aspnet-core\src\MyCompanyName.MyProjectName.DbMigrator\appsettings.json`.
- `templates\app\aspnet-core\src\MyCompanyName.MyProjectName.DbMigrator\appsettings.json`
Ensure that the connection string uses the correct server name (`localhost,1433` by default), user (`sa`), and your password.
### 2. Run the DbMigrator
The DbMigrator project creates the initial database schema and seed data.
```bash
cd templates/app/aspnet-core/src/MyCompanyName.MyProjectName.DbMigrator
dotnet run
```
Wait until the migration completes successfully.
### 3. Install Client-side Libraries
Before running the backend host, install the client-side libraries:
```bash
cd templates/app/aspnet-core
abp install-libs
```
This command restores the required client-side libraries for the backend.
### 4. Run the Backend Host
Go to the backend HTTP API host project folder. The exact project name may differ based on your template, but it will be similar to:
- `templates\app\aspnet-core\src\MyCompanyName.MyProjectName.HttpApi.HostWithIds`
Run the host:
```bash
cd templates/app/aspnet-core/src/MyCompanyName.MyProjectName.HttpApi.HostWithIds
dotnet run
```
After it starts, the backend API will be available on a localhost URL defined in the project (for example, `https://localhost:44305`, depending on your template).
## Running the Frontend (Angular Dev App)
The Angular workspace is under `npm\ng-packs`. It is an Nx workspace that contains both the dev app and the Angular UI packages.
- Dev app path: `npm\ng-packs\apps\dev-app`
- Package path: `npm\ng-packs\packages\`
The dev app uses local references to the packages under `packages`, so your library changes will be reflected immediately while the dev server is running.
### 1. Install Dependencies
From the dev app folder:
```bash
cd npm/ng-packs/apps/dev-app
yarn
# or, if you prefer npm:
# npm install
```
Choose one package manager (preferably `yarn` if that is what the repository uses) and stick with it.
### 2. Start the Dev Server
```bash
yarn start
# or:
# npm start
```
Before running the backend, you should run the Db migrator project. The DbMigrator created initial tables and values. The path of DbMigrator is `templates\app\aspnet-core\src\MyCompanyName.MyProjectName.DbMigrator`. Open a terminal in the path and execute the command `dotnet run` in terminal
This will start the Angular dev server (via Nx) and open the dev app in your browser. Ensure that the backend API is running so the dev app can connect to it.
One last step before the running the backend is installing client-side libraries. Go to `templates\app\aspnet-core`. Open a terminal in the path and execute the command `abp install-libs` in terminal
## Typical Contribution Workflow
Next step you should go to path of backend host project. The path is `templates\app\aspnet-core\src\MyCompanyName.MyProjectName.HttpApi.HostWithIds`. Open a terminal in the path and execute the command `dotnet run` in terminal
1. Start SQL Server and Redis (for example, using the Docker commands above).
2. Run DbMigrator to create and seed the database.
3. Run `abp install-libs` and start the backend HTTP API host.
4. Install dependencies and start the Angular dev app.
5. Make changes in the Angular UI packages under `npm\ng-packs\packages\`.
6. Run any relevant tests for the affected packages (for example, via Nx).
7. Commit your changes and open a pull request on GitHub, referencing the related issue.
Your backend should be running successfully
## Troubleshooting
## Running Frontend App
- **Backend cannot connect to SQL Server**
- Check that the SQL Server container is running (`docker ps`).
- Verify the connection string server/port and `SA_PASSWORD` value.
- **Angular app cannot reach the backend API**
- Confirm that the backend host is running and listening on the expected URL.
- Check the API base URL configuration in the dev app’s environment files.
- **Node or package manager version issues**
- Use an LTS version of Node.js.
- Consider using a version manager (like `nvm`) to match the version used in the project.
There is a demo app. The path of the demo app is `npm\ng-packs\apps\dev-app`. The demo app is connected to the packages with local references. Open the terminal in `npm\ng-packs\apps\dev-app` and execute `yarn` or `npm i` in terminal. After the package installed run `npm start` or `yarn start`.
## See Also
The repo uses Nx and packages connected with `local references`. The packages path is `npm\ng-packs\packages`
- [Contribution Guide](index.md)
- [ABP CLI](https://docs.abp.io/en/abp/latest/cli)

4
docs/en/docs-nav.json

@ -807,6 +807,10 @@
"text": "Object to Object Mapping",
"path": "framework/infrastructure/object-to-object-mapping.md"
},
{
"text": "Operation Rate Limiting",
"path": "framework/infrastructure/operation-rate-limiting.md"
},
{
"text": "Settings",
"path": "framework/infrastructure/settings.md"

4
docs/en/framework/infrastructure/background-jobs/tickerq.md

@ -95,13 +95,13 @@ public class CleanupJobs
public override Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context)
{
var abpTickerQFunctionProvider = context.ServiceProvider.GetRequiredService<AbpTickerQFunctionProvider>();
abpTickerQFunctionProvider.Functions.TryAdd(nameof(CleanupJobs), (string.Empty, TickerTaskPriority.Normal, new TickerFunctionDelegate(async (cancellationToken, serviceProvider, tickerFunctionContext) =>
abpTickerQFunctionProvider.AddFunction(nameof(CleanupJobs), async (cancellationToken, serviceProvider, tickerFunctionContext) =>
{
var service = new CleanupJobs(); // Or get it from the serviceProvider
var request = await TickerRequestProvider.GetRequestAsync<string>(tickerFunctionContext, cancellationToken);
var genericContext = new TickerFunctionContext<string>(tickerFunctionContext, request);
await service.CleanupLogsAsync(genericContext, cancellationToken);
})));
}, TickerTaskPriority.Normal);
abpTickerQFunctionProvider.RequestTypes.TryAdd(nameof(CleanupJobs), (typeof(string).FullName, typeof(string)));
return Task.CompletedTask;
}

8
docs/en/framework/infrastructure/background-workers/tickerq.md

@ -83,13 +83,13 @@ public class CleanupJobs
public override Task OnPreApplicationInitializationAsync(ApplicationInitializationContext context)
{
var abpTickerQFunctionProvider = context.ServiceProvider.GetRequiredService<AbpTickerQFunctionProvider>();
abpTickerQFunctionProvider.Functions.TryAdd(nameof(CleanupJobs), (string.Empty, TickerTaskPriority.Normal, new TickerFunctionDelegate(async (cancellationToken, serviceProvider, tickerFunctionContext) =>
abpTickerQFunctionProvider.AddFunction(nameof(CleanupJobs), async (cancellationToken, serviceProvider, tickerFunctionContext) =>
{
var service = new CleanupJobs(); // Or get it from the serviceProvider
var request = await TickerRequestProvider.GetRequestAsync<string>(tickerFunctionContext, cancellationToken);
var genericContext = new TickerFunctionContext<string>(tickerFunctionContext, request);
await service.CleanupLogsAsync(genericContext, cancellationToken);
})));
}, TickerTaskPriority.Normal);
abpTickerQFunctionProvider.RequestTypes.TryAdd(nameof(CleanupJobs), (typeof(string).FullName, typeof(string)));
return Task.CompletedTask;
}
@ -112,11 +112,11 @@ await cronTickerManager.AddAsync(new CronTickerEntity
You can specify a cron expression instead of using `ICronTickerManager<CronTickerEntity>` to add a worker:
```csharp
abpTickerQFunctionProvider.Functions.TryAdd(nameof(CleanupJobs), (string.Empty, TickerTaskPriority.Normal, new TickerFunctionDelegate(async (cancellationToken, serviceProvider, tickerFunctionContext) =>
abpTickerQFunctionProvider.AddFunction(nameof(CleanupJobs), async (cancellationToken, serviceProvider, tickerFunctionContext) =>
{
var service = new CleanupJobs();
var request = await TickerRequestProvider.GetRequestAsync<string>(tickerFunctionContext, cancellationToken);
var genericContext = new TickerFunctionContext<string>(tickerFunctionContext, request);
await service.CleanupLogsAsync(genericContext, cancellationToken);
})));
}, TickerTaskPriority.Normal);
```

90
docs/en/framework/infrastructure/entity-cache.md

@ -26,7 +26,7 @@ public class Product : AggregateRoot<Guid>
public string Name { get; set; }
public string Description { get; set; }
public float Price { get; set; }
public decimal Price { get; set; }
public int StockCount { get; set; }
}
```
@ -72,7 +72,7 @@ public class ProductDto : EntityDto<Guid>
{
public string Name { get; set; }
public string Description { get; set; }
public float Price { get; set; }
public decimal Price { get; set; }
public int StockCount { get; set; }
}
```
@ -147,6 +147,92 @@ context.Services.AddEntityCache<Product, ProductDto, Guid>(
* Entity classes should be serializable/deserializable to/from JSON to be cached (because it's serialized to JSON when saving in the [Distributed Cache](../fundamentals/caching.md)). If your entity class is not serializable, you can consider using a cache-item/DTO class instead, as explained before.
* Entity Caching System is designed as **read-only**. You should use the standard [repository](../architecture/domain-driven-design/repositories.md) methods to manipulate the entity if you need to. If you need to manipulate (update) the entity, do not get it from the entity cache. Instead, read it from the repository, change it and update using the repository.
## Getting Multiple Entities
In addition to the single-entity methods `FindAsync` and `GetAsync`, the `IEntityCache` service also provides `FindManyAsync` and `GetManyAsync` methods for retrieving multiple entities at once:
```csharp
public class ProductAppService : ApplicationService, IProductAppService
{
private readonly IEntityCache<ProductDto, Guid> _productCache;
public ProductAppService(IEntityCache<ProductDto, Guid> productCache)
{
_productCache = productCache;
}
public async Task<List<ProductDto>> GetManyAsync(List<Guid> ids)
{
return await _productCache.GetManyAsync(ids);
}
public async Task<List<ProductDto?>> FindManyAsync(List<Guid> ids)
{
return await _productCache.FindManyAsync(ids);
}
}
```
* `GetManyAsync` throws `EntityNotFoundException` if any entity is not found for the given IDs.
* `FindManyAsync` returns a list where each entry corresponds to the given ID in the same order; an entry will be `null` if the entity was not found.
Both methods internally use `IDistributedCache.GetOrAddManyAsync` to batch-fetch only the cache-missed entities from the database, making them more efficient than calling `FindAsync` or `GetAsync` in a loop.
## Custom Object Mapping
When you need full control over how an entity is mapped to a cache item, you can derive from `EntityCacheWithObjectMapper` and override the `MapToValue` method:
First, define the cache item class:
```csharp
public class ProductCacheDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
```
Then, derive from `EntityCacheWithObjectMapper` and override `MapToValue`:
```csharp
public class ProductEntityCache :
EntityCacheWithObjectMapper<Product, ProductCacheDto, Guid>
{
public ProductEntityCache(
IReadOnlyRepository<Product, Guid> repository,
IDistributedCache<EntityCacheItemWrapper<ProductCacheDto>, Guid> cache,
IUnitOfWorkManager unitOfWorkManager,
IObjectMapper objectMapper)
: base(repository, cache, unitOfWorkManager, objectMapper)
{
}
protected override ProductCacheDto MapToValue(Product entity)
{
// Custom mapping logic here
return new ProductCacheDto
{
Id = entity.Id,
Name = entity.Name.ToUpperInvariant(),
Price = entity.Price
};
}
}
```
Register your custom cache class in the `ConfigureServices` method of your [module class](../architecture/modularity/basics.md):
```csharp
context.Services.ReplaceEntityCache<ProductEntityCache, Product, ProductCacheDto, Guid>(
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
```
> If no prior `AddEntityCache` registration exists for the same cache item type, `ReplaceEntityCache` will simply add the service instead of throwing an error.
## See Also
* [Distributed caching](../fundamentals/caching.md)

564
docs/en/framework/infrastructure/operation-rate-limiting.md

@ -0,0 +1,564 @@
````json
//[doc-seo]
{
"Description": "Learn how to use the Operation Rate Limiting module in ABP Framework to control the frequency of specific operations like SMS sending, login attempts, and resource-intensive tasks."
}
````
# Operation Rate Limiting
ABP provides an operation rate limiting system that allows you to control the frequency of specific operations in your application. You may need operation rate limiting for several reasons:
* Do not allow sending an SMS verification code to the same phone number more than 3 times in an hour.
* Do not allow generating a "monthly sales report" more than 2 times per day for each user (if generating the report is resource-intensive).
* Restrict login attempts per IP address to prevent brute-force attacks.
> This is not for [ASP.NET Core's built-in rate limiting middleware](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit) which works at the HTTP request pipeline level. This module works at the **application/domain code level** and is called explicitly from your services. See the [Combining with ASP.NET Core Rate Limiting](#combining-with-aspnet-core-rate-limiting) section for a comparison.
## Installation
You can open a command-line terminal and type the following command to install the [Volo.Abp.OperationRateLimiting](https://www.nuget.org/packages/Volo.Abp.OperationRateLimiting) package into your project:
````bash
abp add-package Volo.Abp.OperationRateLimiting
````
> If you haven't done it yet, you first need to install the [ABP CLI](../../../cli).
## Quick Start
This section shows the basic usage of the operation rate limiting system with a simple example.
### Defining a Policy
First, define a rate limiting policy in the `ConfigureServices` method of your [module class](../../architecture/modularity/basics.md):
````csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.AddPolicy("SendSmsCode", policy =>
{
policy.WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)
.PartitionByParameter();
});
});
````
* `"SendSmsCode"` is a unique name for this policy.
* `WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)` means at most **1 request per minute**.
* `PartitionByParameter()` means the counter is keyed by the parameter you pass at check time (e.g., a phone number), so different phone numbers have independent counters.
### Checking the Limit
Then inject `IOperationRateLimitingChecker` and call `CheckAsync` in your service:
````csharp
public class SmsAppService : ApplicationService
{
private readonly IOperationRateLimitingChecker _rateLimitChecker;
public SmsAppService(IOperationRateLimitingChecker rateLimitChecker)
{
_rateLimitChecker = rateLimitChecker;
}
public async Task SendCodeAsync(string phoneNumber)
{
await _rateLimitChecker.CheckAsync("SendSmsCode", phoneNumber);
// If we reach here, the limit was not exceeded.
// Send the SMS code...
}
}
````
* `CheckAsync` increments the counter and throws `AbpOperationRateLimitingException` (HTTP 429) if the limit is exceeded.
* Each phone number has its own counter because we used `PartitionByParameter()`.
* Passing `phoneNumber` directly is a shortcut for `new OperationRateLimitingContext { Parameter = phoneNumber }`. Extension methods are provided for all four methods (`CheckAsync`, `IsAllowedAsync`, `GetStatusAsync`, `ResetAsync`) when you only need to pass a `parameter` string.
That's the basic usage. The following sections explain each concept in detail.
## Defining Policies
Policies are defined using `AbpOperationRateLimitingOptions` in the `ConfigureServices` method of your [module class](../../architecture/modularity/basics.md). Each policy has a unique name, one or more rules, and a partition strategy.
### Single-Rule Policies
For simple scenarios, use the `WithFixedWindow` shortcut directly on the policy builder:
````csharp
options.AddPolicy("SendSmsCode", policy =>
{
policy.WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)
.PartitionByParameter();
});
````
### Multi-Rule Policies
Use `AddRule` to combine multiple rules. All rules are checked together (**AND** logic) — a request is allowed only when **all** rules pass:
````csharp
options.AddPolicy("Login", policy =>
{
// Rule 1: Max 5 attempts per 5 minutes per username
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromMinutes(5), maxCount: 5)
.PartitionByParameter());
// Rule 2: Max 20 attempts per hour per IP
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 20)
.PartitionByClientIp());
});
````
> When multiple rules are present, the module uses a **two-phase check**: it first verifies all rules without incrementing counters, then increments only if all rules pass. This prevents wasted quota when one rule would block the request.
### Overriding an Existing Policy
If a reusable module (e.g., ABP's Account module) defines a policy with default rules, you have two ways to customize it in your own module's `ConfigureServices`.
**Option 1 — Full replacement with `AddPolicy`:**
Call `AddPolicy` with the same name. The last registration wins and completely replaces all rules:
````csharp
// In your application module — runs after the Account module
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.AddPolicy("Account.SendPasswordResetCode", policy =>
{
// Replaces all rules defined by the Account module for this policy
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromMinutes(5), maxCount: 3)
.PartitionByEmail());
});
});
````
> `AddPolicy` stores policies in a dictionary keyed by name, so calling it again with the same name fully replaces the previous policy and all its rules.
**Option 2 — Partial modification with `ConfigurePolicy`:**
Use `ConfigurePolicy` to modify an existing policy without replacing it entirely. The builder is pre-populated with the existing rules, so you only need to express what changes:
````csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
// Only override the error code, keeping the module's original rules
options.ConfigurePolicy("Account.SendPasswordResetCode", policy =>
{
policy.WithErrorCode("MyApp:SmsCodeLimit");
});
});
````
You can also add a rule on top of the existing ones:
````csharp
options.ConfigurePolicy("Account.SendPasswordResetCode", policy =>
{
// Keep the module's per-email rule and add a per-IP rule on top
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 20)
.PartitionByClientIp());
});
````
Or clear all inherited rules first and define entirely new ones using `ClearRules()`:
````csharp
options.ConfigurePolicy("Account.SendPasswordResetCode", policy =>
{
policy.ClearRules()
.WithFixedWindow(TimeSpan.FromMinutes(5), maxCount: 3)
.PartitionByEmail();
});
````
`ConfigurePolicy` returns `AbpOperationRateLimitingOptions`, so you can chain multiple calls:
````csharp
options
.ConfigurePolicy("Account.SendPasswordResetCode", p => p.WithErrorCode("MyApp:SmsLimit"))
.ConfigurePolicy("Account.Login", p => p.WithErrorCode("MyApp:LoginLimit"));
````
> `ConfigurePolicy` throws `AbpException` if the policy name is not found. Use `AddPolicy` first (in the module that owns the policy), then `ConfigurePolicy` in downstream modules to customize it.
### Custom Error Code
By default, the exception uses the error code `Volo.Abp.OperationRateLimiting:010001`. You can override it per policy:
````csharp
options.AddPolicy("SendSmsCode", policy =>
{
policy.WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)
.PartitionByParameter()
.WithErrorCode("App:SmsCodeLimit");
});
````
## Partition Types
Each rule must specify a **partition type** that determines how requests are grouped. Requests with different partition keys have independent counters.
### PartitionByParameter
Uses the `Parameter` value from the context you pass to `CheckAsync`:
````csharp
policy.WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)
.PartitionByParameter();
// Each phone number has its own counter
await checker.CheckAsync("SendSmsCode",
new OperationRateLimitingContext { Parameter = phoneNumber });
````
### PartitionByCurrentUser
Uses `ICurrentUser.Id` as the partition key. The user must be authenticated:
````csharp
policy.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 10)
.PartitionByCurrentUser();
````
> If you need to check rate limits for a specific user (e.g., admin checking another user's limit), use `PartitionByParameter()` and pass the user ID as the `Parameter`.
### PartitionByCurrentTenant
Uses `ICurrentTenant.Id` as the partition key. Uses `"host"` for the host side when no tenant is active:
````csharp
policy.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 100)
.PartitionByCurrentTenant();
````
### PartitionByClientIp
Uses `IWebClientInfoProvider.ClientIpAddress` as the partition key:
````csharp
policy.WithFixedWindow(TimeSpan.FromMinutes(15), maxCount: 10)
.PartitionByClientIp();
````
> This requires an ASP.NET Core environment. In non-web scenarios, the IP address cannot be determined and an exception will be thrown. Use `PartitionByParameter()` if you need to pass the IP explicitly.
### PartitionByEmail
Resolves from `context.Parameter` first, then falls back to `ICurrentUser.Email`:
````csharp
policy.WithFixedWindow(TimeSpan.FromMinutes(1), maxCount: 1)
.PartitionByEmail();
// For unauthenticated users, pass the email explicitly:
await checker.CheckAsync("SendEmailCode",
new OperationRateLimitingContext { Parameter = email });
````
### PartitionByPhoneNumber
Works the same way as `PartitionByEmail`: resolves from `context.Parameter` first, then falls back to `ICurrentUser.PhoneNumber`.
### Custom Partition (PartitionBy)
You can provide a custom async function to generate the partition key. The async signature allows you to perform database queries or other I/O operations:
````csharp
policy.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 100)
.PartitionBy(ctx => Task.FromResult(
$"{ctx.Parameter}:{ctx.ExtraProperties["DeviceId"]}"));
````
## Multi-Tenancy
By default, partition keys do not include tenant information — for partition types like `PartitionByParameter`, `PartitionByCurrentUser`, `PartitionByClientIp`, etc., counters are shared across tenants unless you call `WithMultiTenancy()`. Note that `PartitionByCurrentTenant()` is inherently per-tenant since the partition key is the tenant ID itself, and `PartitionByClientIp()` is typically kept global since the same IP should share a counter regardless of tenant.
You can enable tenant isolation for a rule by calling `WithMultiTenancy()`:
````csharp
policy.AddRule(rule => rule
.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 5)
.WithMultiTenancy()
.PartitionByParameter());
````
When multi-tenancy is enabled, the cache key includes the tenant ID, so each tenant has independent counters:
* **Global key format:** `orl:{PolicyName}:{RuleKey}:{PartitionKey}`
* **Tenant-isolated key format:** `orl:t:{TenantId}:{PolicyName}:{RuleKey}:{PartitionKey}`
## Checking the Limit
Inject `IOperationRateLimitingChecker` to interact with rate limits. It provides four methods:
### CheckAsync
The primary method. It checks the rate limit and **increments the counter** if allowed. Throws `AbpOperationRateLimitingException` (HTTP 429) if the limit is exceeded:
````csharp
await checker.CheckAsync("SendSmsCode",
new OperationRateLimitingContext { Parameter = phoneNumber });
````
### IsAllowedAsync
A read-only check that returns `true` or `false` **without incrementing** the counter. Useful for UI pre-checks (e.g., disabling a button before the user clicks):
````csharp
var isAllowed = await checker.IsAllowedAsync("SendSmsCode",
new OperationRateLimitingContext { Parameter = phoneNumber });
````
### GetStatusAsync
Returns detailed status information **without incrementing** the counter:
````csharp
var status = await checker.GetStatusAsync("SendSmsCode",
new OperationRateLimitingContext { Parameter = phoneNumber });
// status.IsAllowed - whether the next request would be allowed
// status.RemainingCount - how many requests are left in this window
// status.RetryAfter - time until the window resets
// status.MaxCount - maximum allowed count
// status.CurrentCount - current usage count
````
### ResetAsync
Resets the counter for a specific policy and context. This can be useful for administrative operations:
````csharp
await checker.ResetAsync("SendSmsCode",
new OperationRateLimitingContext { Parameter = phoneNumber });
````
## The Exception
When a rate limit is exceeded, `CheckAsync` throws `AbpOperationRateLimitingException`. This exception:
* Extends `BusinessException` and implements `IHasHttpStatusCode` with status code **429** (Too Many Requests).
* Is automatically handled by ABP's exception handling pipeline and serialized into the HTTP response.
The exception uses one of two error codes depending on the policy type:
| Error Code | Constant | When Used |
|---|---|---|
| `Volo.Abp.OperationRateLimiting:010001` | `AbpOperationRateLimitingErrorCodes.ExceedLimit` | Regular rate limit exceeded (has a retry-after window) |
| `Volo.Abp.OperationRateLimiting:010002` | `AbpOperationRateLimitingErrorCodes.ExceedLimitPermanently` | Ban policy (`maxCount: 0`, permanently denied) |
You can override the error code per policy using `WithErrorCode()`. When a custom code is set, it is always used regardless of the policy type.
The exception includes the following data properties:
| Key | Type | Description |
|-----|------|-------------|
| `PolicyName` | string | Name of the triggered policy |
| `MaxCount` | int | Maximum allowed count |
| `CurrentCount` | int | Current usage count |
| `RemainingCount` | int | Remaining allowed count |
| `RetryAfterSeconds` | int | Seconds until the window resets (`0` for ban policies) |
| `RetryAfterMinutes` | int | Minutes until the window resets, rounded down (`0` for ban policies) |
| `RetryAfter` | string | Localized retry-after description (e.g., "5 minutes"); absent for ban policies |
| `WindowDurationSeconds` | int | Total window duration in seconds |
| `WindowDescription` | string | Localized window description |
| `RuleDetails` | List | Per-rule details (for multi-rule policies) |
## Configuration
### AbpOperationRateLimitingOptions
`AbpOperationRateLimitingOptions` is the main options class for the operation rate limiting system:
````csharp
Configure<AbpOperationRateLimitingOptions>(options =>
{
options.IsEnabled = true;
options.LockTimeout = TimeSpan.FromSeconds(5);
});
````
* **`IsEnabled`** (`bool`, default: `true`): Global switch to enable or disable rate limiting. When set to `false`, all `CheckAsync` calls pass through without checking. This is useful for disabling rate limiting in development (see [below](#disabling-in-development)).
* **`LockTimeout`** (`TimeSpan`, default: `5 seconds`): Timeout for acquiring the distributed lock during counter increment operations.
## Advanced Usage
### Disabling in Development
You may want to disable rate limiting during development to avoid being blocked while testing:
````csharp
public override void ConfigureServices(ServiceConfigurationContext context)
{
var hostEnvironment = context.Services.GetHostingEnvironment();
Configure<AbpOperationRateLimitingOptions>(options =>
{
if (hostEnvironment.IsDevelopment())
{
options.IsEnabled = false;
}
});
}
````
### Ban Policy (maxCount: 0)
Setting `maxCount` to `0` creates a ban policy that permanently denies all requests regardless of the window duration. The `RetryAfter` value will be `null` since there is no window to wait for. The exception uses the error code `Volo.Abp.OperationRateLimiting:010002` (`AbpOperationRateLimitingErrorCodes.ExceedLimitPermanently`) with the message "Operation rate limit exceeded. This request is permanently denied.":
````csharp
options.AddPolicy("BlockedUser", policy =>
{
policy.WithFixedWindow(TimeSpan.FromHours(24), maxCount: 0)
.PartitionByParameter();
});
````
### Passing Extra Properties
Use `ExtraProperties` on `OperationRateLimitingContext` to pass additional context data. These values are available in custom partition resolvers and are included in the exception data when the limit is exceeded:
````csharp
await checker.CheckAsync("ApiCall", new OperationRateLimitingContext
{
Parameter = apiEndpoint,
ExtraProperties =
{
["DeviceId"] = deviceId,
["ClientVersion"] = clientVersion
}
});
````
### Pre-checking Before Expensive Operations
Use `IsAllowedAsync` or `GetStatusAsync` to check the limit **before** performing expensive work (e.g., validating input or querying the database):
````csharp
public async Task<SendCodeResultDto> SendCodeAsync(string phoneNumber)
{
var context = new OperationRateLimitingContext { Parameter = phoneNumber };
// Check limit before doing any work
var status = await _rateLimitChecker.GetStatusAsync("SendSmsCode", context);
if (!status.IsAllowed)
{
return new SendCodeResultDto
{
Success = false,
RetryAfterSeconds = (int)(status.RetryAfter?.TotalSeconds ?? 0)
};
}
// Now do the actual work and increment the counter
await _rateLimitChecker.CheckAsync("SendSmsCode", context);
await _smsSender.SendAsync(phoneNumber, GenerateCode());
return new SendCodeResultDto { Success = true };
}
````
> `IsAllowedAsync` and `GetStatusAsync` are read-only — they do not increment the counter. Only `CheckAsync` increments.
### Checking on Behalf of Another User
`PartitionByCurrentUser()`, `PartitionByCurrentTenant()`, and `PartitionByClientIp()` always resolve from their respective services (`ICurrentUser`, `ICurrentTenant`, `IWebClientInfoProvider`) and do not accept explicit overrides. This design avoids partition key conflicts in [composite policies](#multi-rule-policies) where `Parameter` is shared across all rules.
If you need to check or enforce rate limits for a **specific user, tenant, or IP**, define the policy with `PartitionByParameter()` and pass the value explicitly:
````csharp
// Policy definition: use PartitionByParameter for explicit control
options.AddPolicy("UserApiLimit", policy =>
{
policy.WithFixedWindow(TimeSpan.FromHours(1), maxCount: 100)
.PartitionByParameter();
});
````
````csharp
// Check current user's limit
await checker.CheckAsync("UserApiLimit",
new OperationRateLimitingContext { Parameter = CurrentUser.Id.ToString() });
// Admin checking another user's limit
await checker.CheckAsync("UserApiLimit",
new OperationRateLimitingContext { Parameter = targetUserId.ToString() });
// Check a specific IP in a background job
await checker.CheckAsync("UserApiLimit",
new OperationRateLimitingContext { Parameter = ipAddress });
````
This approach gives you full flexibility while keeping the API simple — `PartitionByCurrentUser()` is a convenience shortcut for "always use the current authenticated user", and `PartitionByParameter()` is for "I want to specify the value explicitly".
### Combining with ASP.NET Core Rate Limiting
This module and ASP.NET Core's built-in [rate limiting middleware](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit) serve different purposes and can be used together:
| | ASP.NET Core Rate Limiting | Operation Rate Limiting |
|---|---|---|
| **Level** | HTTP request pipeline | Application/domain code |
| **Scope** | All incoming requests | Specific business operations |
| **Usage** | Middleware (automatic) | Explicit `CheckAsync` calls |
| **Typical use** | API throttling, DDoS protection | Business logic limits (SMS, reports) |
A common pattern is to use ASP.NET Core middleware for broad API protection and this module for fine-grained business operation limits.
## Extensibility
### Custom Store
The default store uses ABP's `IDistributedCache`. You can replace it by implementing `IOperationRateLimitingStore`:
````csharp
public class MyCustomStore : IOperationRateLimitingStore, ITransientDependency
{
public Task<OperationRateLimitingStoreResult> IncrementAsync(
string key, TimeSpan duration, int maxCount)
{
// Your custom implementation (e.g., Redis Lua script for atomicity)
}
public Task<OperationRateLimitingStoreResult> GetAsync(
string key, TimeSpan duration, int maxCount)
{
// Read-only check
}
public Task ResetAsync(string key)
{
// Reset the counter
}
}
````
ABP's [dependency injection](../../fundamentals/dependency-injection.md) system will automatically use your implementation since it replaces the default one.
### Custom Rule
You can implement custom rate limiting algorithms (e.g., sliding window, token bucket) by implementing `IOperationRateLimitingRule` and registering it with `AddRule<TRule>()`:
````csharp
policy.AddRule<MySlidingWindowRule>();
````
### Custom Formatter
Replace `IOperationRateLimitingFormatter` to customize how time durations are displayed in error messages (e.g., "5 minutes", "2 hours 30 minutes").
### Custom Policy Provider
Replace `IOperationRateLimitingPolicyProvider` to load policies from a database or external configuration source instead of the in-memory options.
## See Also
* [ASP.NET Core Rate Limiting Middleware](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit)
* [Distributed Caching](../fundamentals/caching.md)
* [Exception Handling](../fundamentals/exception-handling.md)

82
docs/en/framework/ui/angular/extensions-overall.md

@ -32,10 +32,78 @@ Using [ngx-datatable](https://github.com/swimlane/ngx-datatable) in extensible t
/>
````
* ` actionsText : ` ** Column name of action column. **Type** : string
* ` data : ` Items shows in your table. **Type** : Array<any>
* ` list : ` Instance of ListService. **Type** : ListService
* `actionsColumnWidth : ` Width of your action column. **Type** : number
* ` actionsTemplate : ` Template of the action when "click this button" or whatever. Generally ng-template. **Type** : TemplateRef<any>
* ` recordsTotal : ` Count of the record total. **Type** : number
* ` tableActivate : ` The Output(). A cell or row was focused via the keyboard or a mouse click. **Type** : EventEmitter()
| Input / Output | Description | Type |
|---------------------|----------------------------------------------------------------------------------------------|---------------------|
| `actionsText` | Column name of the action column. | `string` |
| `data` | Items shown in your table. | `Array<any>` |
| `list` | Instance of `ListService`. | `ListService` |
| `actionsColumnWidth`| Width of your action column. | `number` |
| `actionsTemplate` | Template of the action (for example, an `ng-template`). | `TemplateRef<any>` |
| `recordsTotal` | Total count of records. | `number` |
| `tableActivate` | Output fired when a cell or row is focused via keyboard or mouse click. | `EventEmitter` |
### Multiple Selection
The extensible table supports both single-row and multi-row selection. Use the `selectable` input to enable selection, and `selectionType` to control the selection mode.
````ts
<abp-extensible-table
[data]="items"
[recordsTotal]="totalCount"
[list]="list"
[selectable]="true"
[selectionType]="'multiClick'"
[selected]="selectedRows"
(selectionChange)="onSelectionChange($event)"
/>
````
When `selectionType` is `'single'`, each row displays a **radio button** and the header does not show a "select all" checkbox. For all other selection types (e.g. `'multiClick'`, `'checkbox'`), each row shows a **checkbox** and the header includes a "select all" checkbox.
| Input / Output | Description | Type | Default |
|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------|----------------|
| `selectable` | Enables the row selection column. | `boolean` | `false` |
| `selectionType` | Controls the selection mode. Accepts `SelectionType` values such as `'single'`, `'multi'`, `'multiClick'`, `'checkbox'`, or `'cell'`. | `SelectionType | string`| `'multiClick'` |
| `selected` | The currently selected rows. | `any[]` | `[]` |
| `selectionChange` | Output fired when the selection changes. | `EventEmitter<any[]>` | - |
### Infinite Scroll
The extensible table supports infinite scrolling as an alternative to pagination. When enabled, the table emits a `loadMore` event as the user scrolls near the bottom, allowing you to load additional data on demand. Pagination is hidden while infinite scroll is active.
````ts
<abp-extensible-table
[data]="items"
[recordsTotal]="totalCount"
[list]="list"
[infiniteScroll]="true"
[isLoading]="isLoading"
[tableHeight]="500"
[scrollThreshold]="10"
(loadMore)="onLoadMore()"
/>
````
In your component, append newly fetched data to the existing `items` array when `loadMore` fires:
````ts
onLoadMore(): void {
if (this.isLoading) return;
this.isLoading = true;
// fetch next page and append results
this.myService.getList({ skipCount: this.items.length, maxResultCount: 10 }).subscribe(result => {
this.items = [...this.items, ...result.items];
this.isLoading = false;
});
}
````
> **Note:** When `infiniteScroll` is `true`, set a fixed `tableHeight` so the table has a scrollable viewport. Pagination is automatically hidden.
| Input / Output | Description | Type | Default |
|-------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------|-----------|
| `infiniteScroll` | Enables infinite scroll mode (hides pagination). | `boolean` | `false` |
| `isLoading` | Indicates that more data is being fetched. Prevents duplicate `loadMore` events and shows a loading indicator. | `boolean` | `false` |
| `tableHeight` | Fixed height of the table in pixels when `infiniteScroll` is enabled. | `number` | - |
| `scrollThreshold` | Distance from the bottom (in pixels) at which `loadMore` is triggered. | `number` | `10` |
| `loadMore` | Output fired when the user scrolls near the bottom of the table (only when `infiniteScroll` is `true` and `isLoading` is `false`). | `EventEmitter<void>` | - |

142
docs/en/framework/ui/angular/pwa-configuration.md

@ -284,11 +284,53 @@ In addition to updated icons, the library will generate splash screens. However,
## 3. Configure Service Worker
### 3.1 Modify Asset Groups
Once the PWA schematic is installed and the manifest is customized, you should review and tune the Angular service worker configuration.
Angular has defined some static files to be cached by the service worker, but they are not 100% accurate. Let's change it.
The configuration lives in `ngsw-config.json` and controls **what is cached**, **how it is cached**, and **for how long**. See Angular’s [service worker configuration](https://angular.dev/ecosystem/service-workers/config) for full details.
Open _ngsw-config.json_ file and replace its content with this:
### 3.1. Minimal starter configuration
This is a **simple, safe default** that works well for most ABP Angular applications:
```json
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": ["/favicon.ico", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js"]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
]
}
```
- `app` group: prefetches the application shell (HTML, JS, CSS, manifest) so the UI loads quickly and works offline after first visit.
- `assets` group: lazily caches static assets (images, fonts, etc.) as they are requested.
> **Note**: The `"/*.js"` pattern is intentionally generic to work with modern Angular build outputs. Always adapt patterns to match your actual `dist/<project>/browser` files if you customize the build.
### 3.2. Advanced: separate lazy modules
If your app uses many lazy‑loaded feature modules and you want more control over their caching, you can split them into a dedicated group:
```json
{
@ -304,11 +346,10 @@ Open _ngsw-config.json_ file and replace its content with this:
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/common-es2015.*.js",
"/main-es2015.*.js",
"/polyfills-es2015.*.js",
"/runtime-es2015.*.js",
"/vendor-es2015.*.js"
"/main.*.js",
"/polyfills.*.js",
"/runtime.*.js",
"/vendor.*.js"
]
}
},
@ -317,14 +358,7 @@ Open _ngsw-config.json_ file and replace its content with this:
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/*-es2015.*.js",
"!/common-es2015.*.js",
"!/main-es2015.*.js",
"!/polyfills-es2015.*.js",
"!/runtime-es2015.*.js",
"!/vendor-es2015.*.js"
]
"files": ["/*.*.js", "!/main.*.js", "!/polyfills.*.js", "!/runtime.*.js", "!/vendor.*.js"]
}
},
{
@ -334,7 +368,7 @@ Open _ngsw-config.json_ file and replace its content with this:
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
"/*.(eot|svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
@ -342,8 +376,76 @@ Open _ngsw-config.json_ file and replace its content with this:
}
```
In case you want to cache other static files, please refer to the [service worker configuration document](https://angular.dev/ecosystem/service-workers/config) on Angular.dev.
- `app`: core shell bundles that should always be prefetched.
- `modules`: lazy‑loaded feature bundles that are cached only when actually used, then updated in the background.
- `assets`: all static files.
For ABP Angular apps that use `index.csr.html` (CSR/SSR setups), you can add it into the `app` group as well:
```json
"/index.csr.html",
"/index.html",
```
### 3.3. Example `dataGroups` for API caching
`dataGroups` control **HTTP request caching**. This is highly application‑specific, but a small, explicit example is very helpful:
```json
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
// ...
],
"dataGroups": [
{
"name": "api",
"urls": ["/api/**"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 50,
"maxAge": "1h",
"timeout": "5s"
}
}
]
}
```
- `urls`: which HTTP URLs are cached (`/api/**` is an example; narrow this to specific APIs in real apps).
- `strategy: "freshness"`: try network first, fall back to cache if the network is too slow (`timeout`) or offline.
- `maxSize`: maximum number of request entries stored.
- `maxAge`: how long a cached response is considered fresh.
For endpoints where stale data is acceptable and you want faster responses, you can use `"strategy": "performance"` instead.
> **Important**: Be careful not to cache authenticated or highly dynamic endpoints unless you fully understand the implications (stale user data, security, GDPR, etc.).
### 3.4. Build and verify
After changing `ngsw-config.json`:
1. **Build with service worker enabled** (production config):
```bash
ng build --configuration production
```
2. **Serve the built app over HTTP/HTTPS** and open it in the browser.
3. In Chrome DevTools → **Application**:
- **Service Workers**: ensure `ngsw-worker.js` is _installed_ and _controlling the page_.
- **Manifest**: verify the manifest and that the app is installable.
### 3.2 Set Data Groups
4. **Test offline**:
- Load the app once while online.
- Enable “Offline” in DevTools → Network and reload.
- The shell and static assets configured in `assetGroups` should still work.
This part is unique to your project. We recommend being very careful about which endpoints to cache. Please refer to [service worker configuration document](https://angular.dev/ecosystem/service-workers/config) on Angular.dev for details.
For further customization, refer to the official Angular service worker docs:
[https://angular.dev/ecosystem/service-workers/config](https://angular.dev/ecosystem/service-workers/config).

4
docs/en/low-code/custom-endpoints.md

@ -106,7 +106,7 @@ The full [Scripting API](scripting-api.md) (`db` object) is available for queryi
"route": "/api/custom/products/stats",
"method": "GET",
"requireAuthentication": false,
"javascript": "var totalCount = await db.count('LowCodeDemo.Products.Product');\nvar productTable = await db.query('LowCodeDemo.Products.Product');\nvar avgPrice = totalCount > 0 ? await productTable.average(p => p.Price) : 0;\nreturn ok({ totalProducts: totalCount, averagePrice: avgPrice });"
"javascript": "var totalCount = await db.count('LowCodeDemo.Products.Product');\nvar avgPrice = totalCount > 0 ? await db.query('LowCodeDemo.Products.Product').average(p => p.Price) : 0;\nreturn ok({ totalProducts: totalCount, averagePrice: avgPrice });"
}
```
@ -118,7 +118,7 @@ The full [Scripting API](scripting-api.md) (`db` object) is available for queryi
"route": "/api/custom/customers/search",
"method": "GET",
"requireAuthentication": true,
"javascript": "var searchTerm = query.q || '';\nvar customerTable = await db.query('LowCodeDemo.Customers.Customer');\nvar customers = await customerTable\n .where(c => c.Name.toLowerCase().includes(searchTerm.toLowerCase()))\n .take(10)\n .toList();\nreturn ok(customers.map(c => ({ id: c.Id, name: c.Name, email: c.EmailAddress })));"
"javascript": "var searchTerm = query.q || '';\nvar customers = await db.query('LowCodeDemo.Customers.Customer')\n .where(c => c.Name.toLowerCase().includes(searchTerm.toLowerCase()))\n .take(10)\n .toList();\nreturn ok(customers.map(c => ({ id: c.Id, name: c.Name, email: c.EmailAddress })));"
}
```

94
docs/en/low-code/scripting-api.md

@ -21,8 +21,7 @@ The `db` object is the main entry point for all data operations.
```javascript
// Immutable pattern — each call creates a new builder
var entityTable = await db.query('Entity');
var baseQuery = await entityTable.where(x => x.Active);
var baseQuery = db.query('Entity').where(x => x.Active);
var cheap = baseQuery.where(x => x.Price < 100); // baseQuery unchanged
var expensive = baseQuery.where(x => x.Price > 500); // baseQuery unchanged
```
@ -32,15 +31,13 @@ var expensive = baseQuery.where(x => x.Price > 500); // baseQuery unchanged
### Basic Queries
```javascript
var productTable = await db.query('LowCodeDemo.Products.Product');
var products = await productTable
var products = await db.query('LowCodeDemo.Products.Product')
.where(x => x.Price > 100)
.orderBy(x => x.Price)
.take(10)
.toList();
var resultTable = await db.query('LowCodeDemo.Products.Product');
var result = await resultTable
var result = await db.query('LowCodeDemo.Products.Product')
.where(x => x.Price > 100 && x.Price < 500)
.where(x => x.StockCount > 0)
.orderByDescending(x => x.Price)
@ -66,12 +63,9 @@ var result = await resultTable
| `all(x => condition)` | Check if all records match | `Promise<boolean>` |
| `isEmpty()` | Check if no results | `Promise<boolean>` |
| `isSingle()` | Check if exactly one result | `Promise<boolean>` |
| `first()` | Return first match, throws if empty | `Promise<object>` |
| `firstOrDefault()` | Return first match or null | `Promise<object\|null>` |
| `last()` | Return last match, throws if empty | `Promise<object>` |
| `lastOrDefault()` | Return last match or null | `Promise<object\|null>` |
| `single()` | Return single match, throws if empty/multiple | `Promise<object>` |
| `singleOrDefault()` | Return single match or null (throws if multiple) | `Promise<object\|null>` |
| `first()` / `firstOrDefault()` | Return first match or null | `Promise<object\|null>` |
| `last()` / `lastOrDefault()` | Return last match or null | `Promise<object\|null>` |
| `single()` / `singleOrDefault()` | Return single match or null | `Promise<object\|null>` |
| `elementAt(index)` | Return element at index | `Promise<object\|null>` |
| `select(x => projection)` | Project to custom shape | `QueryBuilder` |
| `join(entity, alias, condition)` | Inner join | `QueryBuilder` |
@ -98,18 +92,16 @@ var minPrice = 100;
var config = { minStock: 10 };
var nested = { range: { min: 50, max: 200 } };
var entityTable = await db.query('Entity');
var result = await entityTable.where(x => x.Price > minPrice).toList();
var result2 = await entityTable.where(x => x.StockCount > config.minStock).toList();
var result3 = await entityTable.where(x => x.Price >= nested.range.min).toList();
var result = await db.query('Entity').where(x => x.Price > minPrice).toList();
var result2 = await db.query('Entity').where(x => x.StockCount > config.minStock).toList();
var result3 = await db.query('Entity').where(x => x.Price >= nested.range.min).toList();
```
### Contains / IN Operator
```javascript
var targetPrices = [50, 100, 200];
var entityTable = await db.query('Entity');
var products = await entityTable
var products = await db.query('Entity')
.where(x => targetPrices.includes(x.Price))
.toList();
```
@ -117,8 +109,7 @@ var products = await entityTable
### Select Projection
```javascript
var productTable = await db.query('LowCodeDemo.Products.Product');
var projected = await productTable
var projected = await db.query('LowCodeDemo.Products.Product')
.where(x => x.Price > 0)
.select(x => ({ ProductName: x.Name, ProductPrice: x.Price }))
.toList();
@ -129,8 +120,7 @@ var projected = await productTable
### Explicit Joins
```javascript
var orderLineTable = await db.query('LowCodeDemo.Orders.OrderLine');
var orderLines = await orderLineTable
var orderLines = await db.query('LowCodeDemo.Orders.OrderLine')
.join('LowCodeDemo.Products.Product', 'p', (ol, p) => ol.ProductId === p.Id)
.take(10)
.toList();
@ -145,8 +135,7 @@ orderLines.forEach(line => {
### Left Join
```javascript
var orderTable = await db.query('LowCodeDemo.Orders.Order');
var orders = await orderTable
var orders = await db.query('LowCodeDemo.Orders.Order')
.leftJoin('LowCodeDemo.Products.Product', 'p', (o, p) => o.CustomerId === p.Id)
.toList();
@ -160,22 +149,18 @@ orders.forEach(order => {
### LINQ-Style Join
```javascript
var orderTable = await db.query('Order');
await orderTable.join(
'LowCodeDemo.Products.Product',
o => o.ProductId,
p => p.Id
);
db.query('Order')
.join('LowCodeDemo.Products.Product',
o => o.ProductId,
p => p.Id)
```
### Join with Filtered Query
```javascript
var productTable = await db.query('Product');
var expensiveProducts = await productTable.where(p => p.Price > 100);
var expensiveProducts = db.query('Product').where(p => p.Price > 100);
var orderLineTable = await db.query('OrderLine');
var orders = await orderLineTable
var orders = await db.query('OrderLine')
.join(expensiveProducts,
ol => ol.ProductId,
p => p.Id)
@ -194,9 +179,8 @@ Set operations execute at the database level using SQL:
| `except(query)` | `EXCEPT` | Elements in first, not second |
```javascript
var productTable = await db.query('Product');
var cheap = await productTable.where(x => x.Price <= 100);
var popular = await productTable.where(x => x.Rating > 4);
var cheap = db.query('Product').where(x => x.Price <= 100);
var popular = db.query('Product').where(x => x.Rating > 4);
var bestDeals = await cheap.intersect(popular).toList();
var underrated = await cheap.except(popular).toList();
@ -216,17 +200,15 @@ All aggregations execute as SQL statements:
| `groupBy(x => x.Property)` | `GROUP BY ...` | `Promise<GroupResult[]>` |
```javascript
var productTable = await db.query('Product');
var totalValue = await productTable.sum(x => x.Price);
var avgPrice = await (await productTable.where(x => x.InStock)).average(x => x.Price);
var cheapest = await productTable.min(x => x.Price);
var totalValue = await db.query('Product').sum(x => x.Price);
var avgPrice = await db.query('Product').where(x => x.InStock).average(x => x.Price);
var cheapest = await db.query('Product').min(x => x.Price);
```
### GroupBy with Select
```javascript
var productTable = await db.query('Product');
var grouped = await productTable
var grouped = await db.query('Product')
.groupBy(x => x.Category)
.select(g => ({
Category: g.Key,
@ -255,8 +237,7 @@ var grouped = await productTable
### GroupBy with Items
```javascript
var productTable = await db.query('Product');
var grouped = await productTable
var grouped = await db.query('Product')
.groupBy(x => x.Category)
.select(g => ({
Category: g.Key,
@ -277,12 +258,11 @@ var grouped = await productTable
Math functions translate to SQL functions (ROUND, FLOOR, CEILING, ABS, etc.):
```javascript
var productTable = await db.query('Product');
var products = await productTable
var products = await db.query('Product')
.where(x => Math.round(x.Price) > 100)
.toList();
var result = await productTable
var result = await db.query('Product')
.where(x => Math.abs(x.Balance) < 10 && Math.floor(x.Rating) >= 4)
.toList();
```
@ -400,8 +380,7 @@ All values are parameterized:
```javascript
var malicious = "'; DROP TABLE Products;--";
// Safely treated as a literal string — no injection
var entityTable = await db.query('Entity');
var result = await (await entityTable.where(x => x.Name.includes(malicious))).count();
var result = await db.query('Entity').where(x => x.Name.includes(malicious)).count();
```
### Blocked Features
@ -418,8 +397,7 @@ if (!context.commandArgs.getValue('Email').includes('@')) {
// Try-catch for safe execution
try {
var entityTable = await db.query('Entity');
var products = await entityTable.where(x => x.Price > 0).toList();
var products = await db.query('Entity').where(x => x.Price > 0).toList();
} catch (error) {
context.log('Query failed: ' + error.message);
}
@ -444,8 +422,7 @@ try {
var productId = context.commandArgs.getValue('ProductId');
var quantity = context.commandArgs.getValue('Quantity');
var productTable = await db.query('LowCodeDemo.Products.Product');
var product = await productTable
var product = await db.query('LowCodeDemo.Products.Product')
.where(x => x.Id === productId)
.first();
@ -458,10 +435,11 @@ context.commandArgs.setValue('TotalAmount', product.Price * quantity);
### Sales Dashboard (Custom Endpoint)
```javascript
var orderTable = await db.query('LowCodeDemo.Orders.Order');
var totalOrders = await orderTable.count();
var delivered = await (await orderTable.where(x => x.IsDelivered === true)).count();
var revenue = await (await orderTable.where(x => x.IsDelivered === true)).sum(x => x.TotalAmount);
var totalOrders = await db.query('LowCodeDemo.Orders.Order').count();
var delivered = await db.query('LowCodeDemo.Orders.Order')
.where(x => x.IsDelivered === true).count();
var revenue = await db.query('LowCodeDemo.Orders.Order')
.where(x => x.IsDelivered === true).sum(x => x.TotalAmount);
return ok({
orders: totalOrders,

23
docs/en/package-version-changes.md

@ -1,5 +1,28 @@
# Package Version Changes
## 10.3.0-rc.1
| Package | Old Version | New Version | PR |
|---------|-------------|-------------|-----|
| Microsoft.IdentityModel.JsonWebTokens | 8.14.0 | 8.16.0 | #25068 |
| Microsoft.IdentityModel.Protocols.OpenIdConnect | 8.14.0 | 8.16.0 | #25068 |
| Microsoft.IdentityModel.Tokens | 8.14.0 | 8.16.0 | #25068 |
| System.IdentityModel.Tokens.Jwt | 8.14.0 | 8.16.0 | #25068 |
| TickerQ | 10.1.1 | 10.2.0 | #25091 |
| TickerQ.Dashboard | 10.1.1 | 10.2.0 | #25091 |
| TickerQ.EntityFrameworkCore | 10.1.1 | 10.2.0 | #25091 |
| TickerQ.Utilities | 10.1.1 | 10.2.0 | #25091 |
## 10.3.0-preview
| Package | Old Version | New Version | PR |
|---------|-------------|-------------|-----|
| OpenIddict.Abstractions | 7.2.0 | 7.3.0 | #25053 |
| OpenIddict.Core | 7.2.0 | 7.3.0 | #25053 |
| OpenIddict.Server.AspNetCore | 7.2.0 | 7.3.0 | #25053 |
| OpenIddict.Validation.AspNetCore | 7.2.0 | 7.3.0 | #25053 |
| OpenIddict.Validation.ServerIntegration | 7.2.0 | 7.3.0 | #25053 |
## 10.2.0-rc.1
| Package | Old Version | New Version | PR |

BIN
docs/en/tutorials/modular-crm/images/abp-studio-add-new-standard-module-ui-dialog-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
docs/en/tutorials/modular-crm/images/abp-studio-add-package-reference-dialog-3-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
docs/en/tutorials/modular-crm/images/abp-studio-catalog-module-expanded-in-solution-explorer-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

BIN
docs/en/tutorials/modular-crm/images/abp-studio-imports-and-dependencies-v2-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
docs/en/tutorials/modular-crm/images/abp-studio-install-module-dialog-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

BIN
docs/en/tutorials/modular-crm/images/abp-studio-install-module-dialog-for-ordering-v2-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

BIN
docs/en/tutorials/modular-crm/images/abp-studio-modular-crm-with-standard-module-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

BIN
docs/en/tutorials/modular-crm/images/abp-studio-module-installation-dialog-for-catalog-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

BIN
docs/en/tutorials/modular-crm/images/catalog-module-vs-code-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
docs/en/tutorials/modular-crm/images/vscode-catalog-index-razor-blazor-webapp.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

7
docs/en/tutorials/modular-crm/index.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{

15
docs/en/tutorials/modular-crm/part-01.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -35,7 +42,7 @@ In this first part of this tutorial, we will create a new ABP solution with modu
Follow the *[Get Started](../../get-started/single-layer-web-application.md)* guide to create a single layer web application with the following configuration:
* **Solution name**: `ModularCrm`
* **UI Framework**: {{if UI == "MVC"}}ASP.NET Core MVC / Razor Pages{{else if UI == "NG"}}Angular{{end}}
* **UI Framework**: {{if UI == "MVC"}}ASP.NET Core MVC / Razor Pages{{else if UI == "BlazorWebApp"}}Blazor WebApp{{end}}
* **Database Provider**: Entity Framework Core
{{if UI == "NG"}}> **Note:** Angular users can continue with the Angular UI steps in the upcoming parts while following the same modularity flow.
@ -72,12 +79,16 @@ Initially, you see a `ModularCrm` solution with two solution folders:
If you expand it, you can see the .NET projects (ABP Studio Packages) of the `ModularCrm.Catalog` module:
{{if UI == "MVC"}}
![abp-studio-catalog-module-expanded-in-solution-explorer](images/abp-studio-catalog-module-expanded-in-solution-explorer.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-catalog-module-expanded-in-solution-explorer](images/abp-studio-catalog-module-expanded-in-solution-explorer-blazor-webapp.png)
{{end}}
- `ModularCrm.Catalog`: The main module project that contains your [entities](../../framework/architecture/domain-driven-design/entities.md), [application service](../../framework/architecture/domain-driven-design/application-services.md) implementations and other business objects
- `ModularCrm.Catalog.Contracts`: Basically contains [application service](../../framework/architecture/domain-driven-design/application-services.md) interfaces and [DTOs](../../framework/architecture/domain-driven-design/data-transfer-objects.md). These interfaces then can be used by client modules for integration purposes or by the user interface to perform use cases related to that module
- `ModularCrm.Catalog.Tests`: Unit and integration tests (if you selected the _Include Tests_ option) for that module
- `ModularCrm.Catalog.UI`: Contains user interface pages and components for the module
- {{if UI == "MVC"}}`ModularCrm.Catalog.UI`: Contains user interface pages and components for the module{{else if UI == "BlazorWebApp"}}`ModularCrm.Catalog.Blazor`: Contains Blazor WebApp user interface pages and components for the module{{end}}
## Summary

15
docs/en/tutorials/modular-crm/part-02.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -32,7 +39,7 @@ In this part, you will install the `ModularCrm.Catalog` module to the main appli
## Installing the Catalog Module to the Main Application
A module does not contain an executable application inside. The `ModularCrm.Catalog.UI` project is just a class library project, not an executable web application. A module should be installed in an executable application to run it.
A module does not contain an executable application inside. The {{if UI == "MVC"}}`ModularCrm.Catalog.UI`{{else if UI == "BlazorWebApp"}}`ModularCrm.Catalog.Blazor`{{end}} project is just a class library project, not an executable web application. A module should be installed in an executable application to run it.
> **Ensure that the web application is not running in [Solution Runner](../../studio/running-applications.md) or in your IDE. Installing a module to a running application will produce errors.**
@ -48,9 +55,13 @@ Select the `ModularCrm.Catalog` module and check the *Install this module* optio
When you click the *OK* button, ABP Studio opens the *Install Module* dialog:
{{if UI == "MVC"}}
![abp-studio-module-installation-dialog-for-catalog](images/abp-studio-module-installation-dialog-for-catalog.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-module-installation-dialog-for-catalog](images/abp-studio-module-installation-dialog-for-catalog-blazor-webapp.png)
{{end}}
Select the `ModularCrm.Catalog` and `ModularCrm.Catalog.UI` packages from the left area and ensure the `ModularCrm` package from the middle area was checked as shown in the preceding figure. Finally, click _OK_.
Select the `ModularCrm.Catalog` and {{if UI == "MVC"}}`ModularCrm.Catalog.UI`{{else if UI == "BlazorWebApp"}}`ModularCrm.Catalog.Blazor`{{end}} packages from the left area. {{if UI == "MVC"}}Ensure `ModularCrm` was checked in the middle area as shown in the preceding figure.{{else if UI == "BlazorWebApp"}}For `ModularCrm.Catalog`, ensure `ModularCrm` is checked. For `ModularCrm.Catalog.Blazor`, ensure both `ModularCrm` and `ModularCrm.Client` are checked in the middle area as shown in the preceding figure.{{end}} Finally, click _OK_.
## Building the Main Application

90
docs/en/tutorials/modular-crm/part-03.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -42,7 +49,11 @@ Open the `ModularCrm.Catalog` module in your favorite IDE. You can right-click t
The `ModularCrm.Catalog` .NET solution should look like the following figure:
{{if UI == "MVC"}}
![catalog-module-vs-code](images/catalog-module-vs-code.png)
{{else if UI == "BlazorWebApp"}}
![catalog-module-vs-code](images/catalog-module-vs-code-blazor-webapp.png)
{{end}}
Add a new `Product` class under the `ModularCrm.Catalog` project:
@ -351,6 +362,8 @@ public partial class ProductToProductDtoMapper : MapperBase<Product, ProductDto>
### Exposing Application Services as HTTP API Controllers
{{if UI == "MVC"}}
> This application doesn't need to expose any functionality as HTTP API, because all the module integration and communication will be done in the same process as a natural aspect of a monolith modular application. However, in this section, we will create HTTP APIs because;
>
> 1. We will use these HTTP API endpoints in development to create some example data.
@ -358,6 +371,8 @@ public partial class ProductToProductDtoMapper : MapperBase<Product, ProductDto>
>
> So, follow the instructions in this section and expose the product application service as an HTTP API endpoint.
{{end}}
To create HTTP API endpoints for the catalog module, you have two options:
* You can create a regular ASP.NET Core Controller class in the `ModularCrm.Catalog` project, inject `IProductAppService` and create wrapper methods for each public method of the product application service. You will do this later while you create the Ordering module. (Also, you can check the `SampleController` class under the **Samples** folder in the `ModularCrm.Catalog` project for an example)
@ -379,6 +394,34 @@ This will tell the ABP framework to create API controllers for the application s
Now, ABP will automatically expose the application services defined in the `ModularCrm.Catalog` project as API controllers. The next section will use these API controllers to create some example products.
{{if UI == "BlazorWebApp"}}
### Configuring Client Proxies for the Catalog Module
Since the Blazor WebApp template has a separate `ModularCrm.Client` project, configure HTTP client proxies for the Catalog contracts in the `ModularCrmClientModule` class:
````csharp
using ModularCrm.Catalog;
[DependsOn(
typeof(CatalogContractsModule)
// ...other dependencies
)]
public class ModularCrmClientModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
...
context.Services.AddHttpClientProxies(typeof(ModularCrmContractsModule).Assembly);
context.Services.AddHttpClientProxies(typeof(CatalogContractsModule).Assembly); // NEW: ADD HttpClientProxies
}
}
````
Also ensure the `ModularCrm.Catalog.Blazor` package is installed for both the `ModularCrm` and `ModularCrm.Client` projects.
{{end}}
### Creating Example Products
This section will create a few example products using the [Swagger UI](../../framework/api-development/swagger.md). Thus, you will have some sample products to show on the UI.
@ -415,6 +458,8 @@ As a first step, you can stop the application on ABP Studio's Solution Runner if
### Creating the Products Page
{{if UI == "MVC"}}
Open the `ModularCrm.Catalog` .NET solution in your IDE, and find the `Pages/Catalog/Index.cshtml` file under the `ModularCrm.Catalog.UI` project:
![vscode-catalog-cshtml](images/vscode-catalog-cshtml.png)
@ -470,7 +515,50 @@ Here, you simply use the `IProductAppService` to get a list of all products and
</abp-card>
````
Right-click the `ModularCrm` application on ABP Studio's solution runner and select the *Start* command:
{{else if UI == "BlazorWebApp"}}
Open the `ModularCrm.Catalog` .NET solution in your IDE, and find the `Pages/Catalog/Index.razor` file under the `ModularCrm.Catalog.Blazor` project.
![vscode-catalog-index-razor-blazor-webapp](images/vscode-catalog-index-razor-blazor-webapp.png)
Replace the `Index.razor` file with the following content:
````razor
@page "/catalog"
@using System.Collections.Generic
@using System.Threading.Tasks
@using ModularCrm.Catalog
@inject IProductAppService ProductAppService
<h1>Products</h1>
<Card>
<CardBody>
<ListGroup>
@foreach (var product in Products)
{
<ListGroupItem>
@product.Name <span class="text-muted">(stock: @product.StockCount)</span>
</ListGroupItem>
}
</ListGroup>
</CardBody>
</Card>
@code {
private List<ProductDto> Products { get; set; } = new();
protected override async Task OnInitializedAsync()
{
Products = await ProductAppService.GetListAsync();
}
}
````
Here, you inject `IProductAppService`, get all products in `OnInitializedAsync`, and then render the result in a simple list.
{{end}}
Right-click the `ModularCrm` application on ABP Studio's Solution Runner and select the *Start* command:
![abp-studio-build-and-restart-application](images/abp-studio-build-and-restart-application.png)

23
docs/en/tutorials/modular-crm/part-04.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -47,10 +54,12 @@ That command opens a dialog to define the properties of the new module:
Set `ModularCrm.Ordering` as the *Module name*, leave the *Output folder* as is and click the *Next* button.
{{if UI == "MVC"}}
![abp-studio-add-new-standard-module-ui-dialog](images/abp-studio-add-new-standard-module-ui-dialog.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-add-new-standard-module-ui-dialog](images/abp-studio-add-new-standard-module-ui-dialog-blazor-webapp.png)
{{end}}
You can choose the type of UI you want to support in your module or select *No UI* if you don't need a user interface. In this example, we'll select the *MVC* option and click *Next*.
You can choose the type of UI you want to support in your module or select *No UI* if you don't need a user interface. In this example, we'll select the {{if UI == "MVC"}}*MVC*{{else if UI == "BlazorWebApp"}}*Blazor WebApp*{{end}} option and click *Next*.
{{else if UI == "NG"}}
@ -68,7 +77,11 @@ You can include or not include unit tests for the new module here. We are unchec
Here is the final solution structure after adding the `ModularCrm.Ordering` module:
{{if UI == "MVC"}}
![abp-studio-modular-crm-with-standard-module](images/abp-studio-modular-crm-with-standard-module.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-modular-crm-with-standard-module](images/abp-studio-modular-crm-with-standard-module-blazor-webapp.png)
{{end}}
## Installing into the Main Application
@ -86,9 +99,13 @@ That command opens the *Import Module* dialog:
Select the `ModularCrm.Ordering` module and check the *Install this module* option as shown in the preceding figure. When you click the OK button, a new dialog is shown to select the packages to install:
{{if UI == "MVC"}}
![abp-studio-install-module-dialog](images/abp-studio-install-module-dialog-v2.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-install-module-dialog](images/abp-studio-install-module-dialog-blazor-webapp.png)
{{end}}
Select the `ModularCrm.Ordering` and `ModularCrm.Ordering.UI` packages from the left area and ensure the `ModularCrm` package from the middle area was checked as shown in the preceding figure. Finally, click _OK_.
Select the `ModularCrm.Ordering` and {{if UI == "MVC"}}`ModularCrm.Ordering.UI`{{else if UI == "BlazorWebApp"}}`ModularCrm.Ordering.Blazor`{{end}} packages from the left area. {{if UI == "MVC"}}Ensure `ModularCrm` was checked in the middle area as shown in the preceding figure.{{else if UI == "BlazorWebApp"}}For `ModularCrm.Ordering`, ensure `ModularCrm` is checked. For `ModularCrm.Ordering.Blazor`, ensure both `ModularCrm` and `ModularCrm.Client` are checked in the middle area as shown in the preceding figure.{{end}} Finally, click _OK_.
{{if UI == "NG"}}

122
docs/en/tutorials/modular-crm/part-05.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -364,6 +371,35 @@ Configure<AbpAspNetCoreMvcOptions>(options =>
This will tell the ABP framework to create API controllers for the application services in the `ModularCrm.Ordering` assembly.
{{if UI == "BlazorWebApp"}}
### Configuring Client Proxies for the Ordering Module
In the `ModularCrm.Client` project, configure HTTP client proxies for the Ordering contracts in the `ModularCrmClientModule` class:
````csharp
using ModularCrm.Ordering;
[DependsOn(
typeof(OrderingContractsModule)
// ...other dependencies
)]
public class ModularCrmClientModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
...
context.Services.AddHttpClientProxies(typeof(ModularCrmContractsModule).Assembly);
context.Services.AddHttpClientProxies(typeof(CatalogContractsModule).Assembly);
context.Services.AddHttpClientProxies(typeof(OrderingContractsModule).Assembly); // NEW: ADD HttpClientProxies
}
}
````
Also ensure the `ModularCrm.Ordering.Blazor` package is installed for both the `ModularCrm` and `ModularCrm.Client` projects.
{{end}}
### Creating Example Orders
This section will create a few example orders using the [Swagger UI](../../framework/api-development/swagger.md). Thus, you will have some sample orders to show on the UI.
@ -394,6 +430,8 @@ As a first step, you can stop the application on ABP Studio's Solution Runner if
### Creating the Orders Page
{{if UI == "MVC"}}
Replace the `Index.cshtml.cs` content in the `Pages/Ordering` folder of the `ModularCrm.Ordering.UI` project with the following code block:
````csharp
@ -490,6 +528,90 @@ public class OrderingMenuContributor : IMenuContributor
> You can check the [menu documentation](../../framework/ui/mvc-razor-pages/navigation-menu.md) to learn more about manipulating menu items.
{{else if UI == "BlazorWebApp"}}
Replace the `Index.razor` content in the `Pages/Ordering` folder of the `ModularCrm.Ordering.Blazor` project with the following code block:
````razor
@page "/ordering"
@using System.Collections.Generic
@using System.Threading.Tasks
@using ModularCrm.Ordering
@inject IOrderAppService OrderAppService
<h1>Orders</h1>
<Card>
<CardBody>
<ListGroup>
@foreach (var order in Orders)
{
<ListGroupItem>
<strong>Customer:</strong> @order.CustomerName <br />
<strong>Product:</strong> @order.ProductId <br />
<strong>State:</strong> @order.State
</ListGroupItem>
}
</ListGroup>
</CardBody>
</Card>
@code {
private List<OrderDto> Orders { get; set; } = new();
protected override async Task OnInitializedAsync()
{
Orders = await OrderAppService.GetListAsync();
}
}
````
This page shows a list of orders on the UI. You haven't created a UI to create new orders, and we will not do it to keep this tutorial simple. If you want to learn how to create advanced UIs with ABP, please follow the [Book Store tutorial](../book-store/index.md).
### Editing the Menu Item
ABP provides a modular navigation [menu system](../../framework/ui/blazor/navigation-menu.md) where each module can contribute to the main menu dynamically.
Edit the `OrderingMenuContributor` class in the `ModularCrm.Ordering.Blazor` project:
````csharp
using System.Threading.Tasks;
using Volo.Abp.UI.Navigation;
namespace ModularCrm.Ordering.Blazor.Menus;
public class OrderingMenuContributor : IMenuContributor
{
public async Task ConfigureMenuAsync(MenuConfigurationContext context)
{
if (context.Menu.Name == StandardMenus.Main)
{
await ConfigureMainMenuAsync(context);
}
}
private Task ConfigureMainMenuAsync(MenuConfigurationContext context)
{
context.Menu.AddItem(
new ApplicationMenuItem(
OrderingMenus.Prefix, // Unique menu id
"Orders", // Menu display text
"/ordering", // URL
"fa-solid fa-basket-shopping" // Icon CSS class
)
);
return Task.CompletedTask;
}
}
````
`OrderingMenuContributor` implements the `IMenuContributor` interface, which forces us to implement the `ConfigureMenuAsync` method. In that method, you can manipulate the menu items (add new menu items, remove existing menu items or change the properties of existing menu items). The `ConfigureMenuAsync` method is executed whenever the menu is rendered on the UI, so you can dynamically decide how to manipulate the menu items.
> You can check the [menu documentation](../../framework/ui/blazor/navigation-menu.md) to learn more about manipulating menu items.
{{end}}
### Building the Application
Now, you will run the application to see the result. Please stop the application if it is already running. Then open the *Solution Runner* panel, right-click the `ModularCrm` application, and select the *Build* -> *Graph Build* command:

53
docs/en/tutorials/modular-crm/part-06.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -145,7 +152,11 @@ Open the ABP Studio UI and stop the application if it is already running. Then o
In the opening dialog, select the *This solution* tab, find and check the `ModularCrm.Catalog.Contracts` package and click the OK button:
{{if UI == "MVC"}}
![abp-studio-add-package-reference-dialog-3](images/abp-studio-add-package-reference-dialog-3.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-add-package-reference-dialog-3](images/abp-studio-add-package-reference-dialog-3-blazor-webapp.png)
{{end}}
ABP Studio adds the package reference and arranges the [module](../../framework/architecture/modularity/basics.md) dependency.
@ -258,7 +269,7 @@ Let's see what we've changed:
{{if UI == "MVC"}}
Open the `Index.cshtml` file, and change the `@order.ProductId` part by `@order.ProductName` to write the product name instead of the product ID. The final `Index.cshtml` content should be the following:
Open the `Index.cshtml` file, and change the `@order.ProductId` part to `@order.ProductName` to write the product name instead of the product ID. The final `Index.cshtml` content should be the following:
````html
@page
@ -282,6 +293,46 @@ Open the `Index.cshtml` file, and change the `@order.ProductId` part by `@order.
</abp-card>
````
{{else if UI == "BlazorWebApp"}}
Open the `Index.razor` file, and change the `@order.ProductId` part to `@order.ProductName` to write the product name instead of the product ID. The final `Index.razor` content should be the following:
````razor
@page "/ordering"
@using System.Collections.Generic
@using System.Threading.Tasks
@using ModularCrm.Ordering
@inject IOrderAppService OrderAppService
<h1>Orders</h1>
<Card>
<CardBody>
<ListGroup>
@foreach (var order in Orders)
{
<ListGroupItem>
<strong>Customer:</strong> @order.CustomerName <br />
<strong>Product:</strong> @order.ProductName <br />
<strong>State:</strong> @order.State
</ListGroupItem>
}
</ListGroup>
</CardBody>
</Card>
@code {
private List<OrderDto> Orders { get; set; } = new();
protected override async Task OnInitializedAsync()
{
Orders = await OrderAppService.GetListAsync();
}
}
````
{{end}}
That's all. Now, you can graph build the main application and run it in ABP Studio to see the result:
![abp-studio-browser-list-of-orders-with-product-name](images/abp-studio-browser-list-of-orders-with-product-name.png)

15
docs/en/tutorials/modular-crm/part-07.md

@ -14,6 +14,13 @@
}
```
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -165,13 +172,21 @@ In the opening dialog, find and select the `ModularCrm.Ordering` module, check t
Once you click the OK button, the Ordering module is imported to the Catalog module, and an installation dialog is open:
{{if UI == "MVC"}}
![abp-studio-install-module-dialog-for-ordering](images/abp-studio-install-module-dialog-for-ordering-v2.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-install-module-dialog-for-ordering](images/abp-studio-install-module-dialog-for-ordering-v2-blazor-webapp.png)
{{end}}
Here, select the `ModularCrm.Ordering.Contracts` package on the left side (because we want to add that package reference) and `ModularCrm.Catalog` package on the middle area (because we want to add the package reference to that project). Also, select the `ModularCrm.Ordering` package on the right side, and unselect all packages on the middle area (we don't need the implementation or any other packages). Then, click the OK button to finish the installation operation.
You can check the ABP Studio's *Solution Explorer* panel to see the module import and the project reference (dependency).
{{if UI == "MVC"}}
![abp-studio-imports-and-dependencies](images/abp-studio-imports-and-dependencies-v2.png)
{{else if UI == "BlazorWebApp"}}
![abp-studio-imports-and-dependencies](images/abp-studio-imports-and-dependencies-v2-blazor-webapp.png)
{{end}}
### Handling the `OrderPlacedEto` Event

9
docs/en/tutorials/modular-crm/part-08.md

@ -14,6 +14,13 @@
# Integrating the Modules: Joining the Products and Orders Data
````json
//[doc-params]
{
"UI": ["MVC","BlazorWebApp"]
}
````
````json
//[doc-nav]
{
@ -176,7 +183,7 @@ Now, you know the fundamental principles and mechanics of building sophisticated
## Download the Source Code
You can download the completed sample solution [here](https://github.com/abpframework/abp-samples/tree/master/ModularCRM).
You can download the completed sample solution [here](https://github.com/abpframework/abp-samples/tree/master/ModularCRM-BlazorWebApp).
## See Also

2
framework/Volo.Abp.slnx

@ -169,6 +169,7 @@
<Project Path="src/Volo.Abp.TickerQ/Volo.Abp.TickerQ.csproj" />
<Project Path="src/Volo.Abp.BackgroundJobs.TickerQ/Volo.Abp.BackgroundJobs.TickerQ.csproj" />
<Project Path="src/Volo.Abp.BackgroundWorkers.TickerQ/Volo.Abp.BackgroundWorkers.TickerQ.csproj" />
<Project Path="src/Volo.Abp.OperationRateLimiting/Volo.Abp.OperationRateLimiting.csproj" />
</Folder>
<Folder Name="/test/">
<Project Path="test/AbpTestBase/AbpTestBase.csproj" />
@ -256,5 +257,6 @@
<Project Path="test/Volo.Abp.Uow.Tests/Volo.Abp.Uow.Tests.csproj" />
<Project Path="test/Volo.Abp.Validation.Tests/Volo.Abp.Validation.Tests.csproj" />
<Project Path="test/Volo.Abp.VirtualFileSystem.Tests/Volo.Abp.VirtualFileSystem.Tests.csproj" />
<Project Path="test/Volo.Abp.OperationRateLimiting.Tests/Volo.Abp.OperationRateLimiting.Tests.csproj" />
</Folder>
</Solution>

2
framework/src/Volo.Abp.AspNetCore.Abstractions/Volo/Abp/AspNetCore/AbpAspNetCoreAbstractionsModule.cs

@ -10,6 +10,6 @@ public class AbpAspNetCoreAbstractionsModule : AbpModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddSingleton<IWebContentFileProvider, NullWebContentFileProvider>();
context.Services.AddSingleton<IWebClientInfoProvider, NullWebClientInfoProvider>();;
context.Services.AddSingleton<IWebClientInfoProvider, NullWebClientInfoProvider>();
}
}

7
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/AbpApiDefinitionController.cs

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Http.Modeling;
namespace Volo.Abp.AspNetCore.Mvc.ApiExploring;
@ -16,8 +17,8 @@ public class AbpApiDefinitionController : AbpController, IRemoteService
}
[HttpGet]
public virtual ApplicationApiDescriptionModel Get(ApplicationApiDescriptionModelRequestDto model)
public virtual async Task<ApplicationApiDescriptionModel> Get(ApplicationApiDescriptionModelRequestDto model)
{
return ModelProvider.CreateApiModel(model);
return await ModelProvider.CreateApiModelAsync(model);
}
}

22
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/IXmlDocumentationProvider.cs

@ -0,0 +1,22 @@
using System;
using System.Reflection;
using System.Threading.Tasks;
namespace Volo.Abp.AspNetCore.Mvc.ApiExploring;
public interface IXmlDocumentationProvider
{
Task<string?> GetSummaryAsync(Type type);
Task<string?> GetRemarksAsync(Type type);
Task<string?> GetSummaryAsync(MethodInfo method);
Task<string?> GetRemarksAsync(MethodInfo method);
Task<string?> GetReturnsAsync(MethodInfo method);
Task<string?> GetParameterSummaryAsync(MethodInfo method, string parameterName);
Task<string?> GetSummaryAsync(PropertyInfo property);
}

231
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/XmlDocumentationProvider.cs

@ -0,0 +1,231 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.AspNetCore.Mvc.ApiExploring;
public class XmlDocumentationProvider : IXmlDocumentationProvider, ISingletonDependency
{
public ILogger<XmlDocumentationProvider> Logger { get; set; }
public XmlDocumentationProvider()
{
Logger = NullLogger<XmlDocumentationProvider>.Instance;
}
private static readonly Regex WhitespaceRegex = new(@"\s+", RegexOptions.Compiled);
// Matches any remaining XML tags like <c>, <code>, <para>, <b>, etc.
private static readonly Regex XmlTagRegex = new(@"<[^>]+>", RegexOptions.Compiled);
// Matches <see cref="T:Foo.Bar"/>, <see langword="null"/>, <paramref name="x"/>, <typeparamref name="T"/>
private static readonly Regex XmlRefTagRegex = new(
@"<(see|paramref|typeparamref)\s+(cref|name|langword)=""([TMFPE]:)?(?<display>[^""]+)""\s*/?>",
RegexOptions.Compiled);
private readonly ConcurrentDictionary<Assembly, Lazy<Task<XDocument?>>> _xmlDocCache = new();
public virtual async Task<string?> GetSummaryAsync(Type type)
{
var memberName = GetMemberNameForType(type);
return await GetDocumentationElementAsync(type.Assembly, memberName, "summary");
}
public virtual async Task<string?> GetRemarksAsync(Type type)
{
var memberName = GetMemberNameForType(type);
return await GetDocumentationElementAsync(type.Assembly, memberName, "remarks");
}
public virtual async Task<string?> GetSummaryAsync(MethodInfo method)
{
var memberName = GetMemberNameForMethod(method);
return await GetDocumentationElementAsync(method.DeclaringType!.Assembly, memberName, "summary");
}
public virtual async Task<string?> GetRemarksAsync(MethodInfo method)
{
var memberName = GetMemberNameForMethod(method);
return await GetDocumentationElementAsync(method.DeclaringType!.Assembly, memberName, "remarks");
}
public virtual async Task<string?> GetReturnsAsync(MethodInfo method)
{
var memberName = GetMemberNameForMethod(method);
return await GetDocumentationElementAsync(method.DeclaringType!.Assembly, memberName, "returns");
}
public virtual async Task<string?> GetParameterSummaryAsync(MethodInfo method, string parameterName)
{
var memberName = GetMemberNameForMethod(method);
var doc = await LoadXmlDocumentationAsync(method.DeclaringType!.Assembly);
if (doc == null)
{
return null;
}
var memberNode = doc.XPathSelectElement($"//member[@name='{memberName}']");
var paramNode = memberNode?.XPathSelectElement($"param[@name='{parameterName}']");
return CleanXmlText(paramNode);
}
public virtual async Task<string?> GetSummaryAsync(PropertyInfo property)
{
var memberName = GetMemberNameForProperty(property);
return await GetDocumentationElementAsync(property.DeclaringType!.Assembly, memberName, "summary");
}
protected virtual async Task<string?> GetDocumentationElementAsync(Assembly assembly, string memberName, string elementName)
{
var doc = await LoadXmlDocumentationAsync(assembly);
if (doc == null)
{
return null;
}
var memberNode = doc.XPathSelectElement($"//member[@name='{memberName}']");
var element = memberNode?.Element(elementName);
return CleanXmlText(element);
}
protected virtual Task<XDocument?> LoadXmlDocumentationAsync(Assembly assembly)
{
return _xmlDocCache.GetOrAdd(
assembly,
asm => new Lazy<Task<XDocument?>>(
() => LoadXmlDocumentationFromDiskAsync(asm),
LazyThreadSafetyMode.ExecutionAndPublication)
).Value;
}
protected virtual async Task<XDocument?> LoadXmlDocumentationFromDiskAsync(Assembly assembly)
{
if (string.IsNullOrEmpty(assembly.Location))
{
return null;
}
var xmlFilePath = Path.ChangeExtension(assembly.Location, ".xml");
if (!File.Exists(xmlFilePath))
{
return null;
}
try
{
await using var stream = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true);
return await XDocument.LoadAsync(stream, LoadOptions.None, CancellationToken.None);
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Failed to load XML documentation from {XmlFilePath}.", xmlFilePath);
return null;
}
}
private static string? CleanXmlText(XElement? element)
{
if (element == null)
{
return null;
}
// Convert to string first so we can process inline XML tags like <see cref="..."/>
var raw = element.ToString();
// Strip the outer element tags (e.g. <summary>...</summary>)
var start = raw.IndexOf('>') + 1;
var end = raw.LastIndexOf('<');
if (start >= end)
{
return null;
}
var inner = raw[start..end];
// Replace <see cref="T:Foo.Bar"/> with the short name "Bar"
// Replace <see langword="null"/> with "null"
// Replace <paramref name="x"/> and <typeparamref name="T"/> with the name
inner = XmlRefTagRegex.Replace(inner, m =>
{
var display = m.Groups["display"].Value;
// For cref values like "T:Foo.Bar.Baz", return only "Baz"
var dot = display.LastIndexOf('.');
return dot >= 0 ? display[(dot + 1)..] : display;
});
// Strip any remaining XML tags (e.g. <c>, <code>, <para>, <b>, etc.)
inner = XmlTagRegex.Replace(inner, string.Empty);
if (string.IsNullOrWhiteSpace(inner))
{
return null;
}
return WhitespaceRegex.Replace(inner.Trim(), " ");
}
private static string GetMemberNameForType(Type type)
{
return $"T:{GetTypeFullName(type)}";
}
private static string GetMemberNameForMethod(MethodInfo method)
{
var typeName = GetTypeFullName(method.DeclaringType!);
var parameters = method.GetParameters();
if (parameters.Length == 0)
{
return $"M:{typeName}.{method.Name}";
}
var paramTypes = string.Join(",",
parameters.Select(p => GetParameterTypeName(p.ParameterType)));
return $"M:{typeName}.{method.Name}({paramTypes})";
}
private static string GetMemberNameForProperty(PropertyInfo property)
{
var typeName = GetTypeFullName(property.DeclaringType!);
return $"P:{typeName}.{property.Name}";
}
private static string GetTypeFullName(Type type)
{
return type.FullName?.Replace('+', '.') ?? type.Name;
}
private static string GetParameterTypeName(Type type)
{
if (type.IsGenericType)
{
var genericDef = type.GetGenericTypeDefinition();
var defName = genericDef.FullName!;
defName = defName[..defName.IndexOf('`')];
var args = string.Join(",", type.GetGenericArguments().Select(GetParameterTypeName));
return $"{defName}{{{args}}}";
}
if (type.IsArray)
{
return GetParameterTypeName(type.GetElementType()!) + "[]";
}
if (type.IsByRef)
{
return GetParameterTypeName(type.GetElementType()!) + "@";
}
return type.FullName ?? type.Name;
}
}

224
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs

@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Asp.Versioning;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authorization;
@ -12,6 +15,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Volo.Abp.AspNetCore.Mvc.ApiExploring;
using Volo.Abp.AspNetCore.Mvc.Conventions;
using Volo.Abp.AspNetCore.Mvc.Utils;
using Volo.Abp.DependencyInjection;
@ -29,26 +33,30 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
private readonly IApiDescriptionGroupCollectionProvider _descriptionProvider;
private readonly AbpAspNetCoreMvcOptions _abpAspNetCoreMvcOptions;
private readonly AbpApiDescriptionModelOptions _modelOptions;
private readonly IXmlDocumentationProvider _xmlDocProvider;
public AspNetCoreApiDescriptionModelProvider(
IOptions<AspNetCoreApiDescriptionModelProviderOptions> options,
IApiDescriptionGroupCollectionProvider descriptionProvider,
IOptions<AbpAspNetCoreMvcOptions> abpAspNetCoreMvcOptions,
IOptions<AbpApiDescriptionModelOptions> modelOptions)
IOptions<AbpApiDescriptionModelOptions> modelOptions,
IXmlDocumentationProvider xmlDocProvider)
{
_options = options.Value;
_descriptionProvider = descriptionProvider;
_abpAspNetCoreMvcOptions = abpAspNetCoreMvcOptions.Value;
_modelOptions = modelOptions.Value;
_xmlDocProvider = xmlDocProvider;
Logger = NullLogger<AspNetCoreApiDescriptionModelProvider>.Instance;
}
public ApplicationApiDescriptionModel CreateApiModel(ApplicationApiDescriptionModelRequestDto input)
public virtual async Task<ApplicationApiDescriptionModel> CreateApiModelAsync(ApplicationApiDescriptionModelRequestDto input)
{
//TODO: Can cache the model?
var model = ApplicationApiDescriptionModel.Create();
var populatedControllers = new HashSet<ControllerApiDescriptionModel>();
foreach (var descriptionGroupItem in _descriptionProvider.ApiDescriptionGroups.Items)
{
@ -59,7 +67,7 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
continue;
}
AddApiDescriptionToModel(apiDescription, model, input);
await AddApiDescriptionToModelAsync(apiDescription, model, input, populatedControllers);
}
}
@ -80,10 +88,11 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
return model;
}
private void AddApiDescriptionToModel(
private async Task AddApiDescriptionToModelAsync(
ApiDescription apiDescription,
ApplicationApiDescriptionModel applicationModel,
ApplicationApiDescriptionModelRequestDto input)
ApplicationApiDescriptionModelRequestDto input,
HashSet<ControllerApiDescriptionModel> populatedControllers)
{
var controllerType = apiDescription
.ActionDescriptor
@ -139,10 +148,21 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
var implementFrom = controllerType.FullName;
var interfaceType = controllerType.GetInterfaces().FirstOrDefault(i => i.GetMethods().Any(x => x.ToString() == method.ToString()));
if (interfaceType != null)
foreach (var iface in controllerType.GetInterfaces())
{
implementFrom = TypeHelper.GetFullNameHandlingNullableAndGenerics(interfaceType);
try
{
var map = controllerType.GetInterfaceMap(iface);
if (Array.IndexOf(map.TargetMethods, method) >= 0)
{
implementFrom = TypeHelper.GetFullNameHandlingNullableAndGenerics(iface);
break;
}
}
catch (ArgumentException)
{
// GetInterfaceMap is not supported for some generic interface edge cases
}
}
var actionModel = controllerModel.AddAction(
@ -161,10 +181,22 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
if (input.IncludeTypes)
{
AddCustomTypesToModel(applicationModel, method);
await AddCustomTypesToModelAsync(applicationModel, method, input.IncludeDescriptions);
}
AddParameterDescriptionsToModel(actionModel, method, apiDescription);
if (input.IncludeDescriptions)
{
if (populatedControllers.Add(controllerModel))
{
await PopulateControllerDescriptionsAsync(controllerModel, controllerType);
}
var interfaceMethod = GetInterfaceMethod(method);
await PopulateActionDescriptionsAsync(actionModel, method, interfaceMethod);
await PopulateParameterDescriptionsAsync(actionModel, method, interfaceMethod);
}
}
private static List<string> GetSupportedVersions(Type controllerType, MethodInfo method,
@ -191,18 +223,18 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
return supportedVersions.Select(v => v.ToString()).Distinct().ToList();
}
private void AddCustomTypesToModel(ApplicationApiDescriptionModel applicationModel, MethodInfo method)
private async Task AddCustomTypesToModelAsync(ApplicationApiDescriptionModel applicationModel, MethodInfo method, bool includeDescriptions)
{
foreach (var parameterInfo in method.GetParameters())
{
AddCustomTypesToModel(applicationModel, parameterInfo.ParameterType);
await AddCustomTypesToModelAsync(applicationModel, parameterInfo.ParameterType, includeDescriptions);
}
AddCustomTypesToModel(applicationModel, method.ReturnType);
await AddCustomTypesToModelAsync(applicationModel, method.ReturnType, includeDescriptions);
}
private static void AddCustomTypesToModel(ApplicationApiDescriptionModel applicationModel,
Type? type)
private async Task AddCustomTypesToModelAsync(ApplicationApiDescriptionModel applicationModel,
Type? type, bool includeDescriptions)
{
if (type == null)
{
@ -229,14 +261,14 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
if (TypeHelper.IsDictionary(type, out var keyType, out var valueType))
{
AddCustomTypesToModel(applicationModel, keyType);
AddCustomTypesToModel(applicationModel, valueType);
await AddCustomTypesToModelAsync(applicationModel, keyType, includeDescriptions);
await AddCustomTypesToModelAsync(applicationModel, valueType, includeDescriptions);
return;
}
if (TypeHelper.IsEnumerable(type, out var itemType))
{
AddCustomTypesToModel(applicationModel, itemType);
await AddCustomTypesToModelAsync(applicationModel, itemType, includeDescriptions);
return;
}
@ -244,11 +276,11 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
AddCustomTypesToModel(applicationModel, genericTypeDefinition);
await AddCustomTypesToModelAsync(applicationModel, genericTypeDefinition, includeDescriptions);
foreach (var genericArgument in type.GetGenericArguments())
{
AddCustomTypesToModel(applicationModel, genericArgument);
await AddCustomTypesToModelAsync(applicationModel, genericArgument, includeDescriptions);
}
return;
@ -262,11 +294,16 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
applicationModel.Types[typeName] = TypeApiDescriptionModel.Create(type);
AddCustomTypesToModel(applicationModel, type.BaseType);
if (includeDescriptions)
{
await PopulateTypeDescriptionsAsync(applicationModel.Types[typeName], type);
}
await AddCustomTypesToModelAsync(applicationModel, type.BaseType, includeDescriptions);
foreach (var propertyInfo in type.GetProperties().Where(p => p.DeclaringType == type))
{
AddCustomTypesToModel(applicationModel, propertyInfo.PropertyType);
await AddCustomTypesToModelAsync(applicationModel, propertyInfo.PropertyType, includeDescriptions);
}
}
@ -414,4 +451,149 @@ public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvide
return null;
}
protected virtual async Task PopulateControllerDescriptionsAsync(ControllerApiDescriptionModel controllerModel, Type controllerType)
{
controllerModel.Summary = await _xmlDocProvider.GetSummaryAsync(controllerType);
controllerModel.Remarks = await _xmlDocProvider.GetRemarksAsync(controllerType);
if (controllerModel.Summary == null && controllerModel.Remarks == null)
{
foreach (var interfaceType in GetDirectInterfaces(controllerType).Where(i => !_modelOptions.IgnoredInterfaces.Contains(i)))
{
controllerModel.Summary = await _xmlDocProvider.GetSummaryAsync(interfaceType);
controllerModel.Remarks = await _xmlDocProvider.GetRemarksAsync(interfaceType);
if (controllerModel.Summary != null || controllerModel.Remarks != null)
{
break;
}
}
}
controllerModel.Description = controllerType.GetCustomAttribute<DescriptionAttribute>()?.Description;
controllerModel.DisplayName = controllerType.GetCustomAttribute<DisplayAttribute>()?.Name;
}
protected virtual async Task PopulateActionDescriptionsAsync(ActionApiDescriptionModel actionModel, MethodInfo method, MethodInfo? interfaceMethod)
{
actionModel.Summary = await _xmlDocProvider.GetSummaryAsync(method);
actionModel.Remarks = await _xmlDocProvider.GetRemarksAsync(method);
if (actionModel.Summary == null && actionModel.Remarks == null && interfaceMethod != null)
{
actionModel.Summary = await _xmlDocProvider.GetSummaryAsync(interfaceMethod);
actionModel.Remarks = await _xmlDocProvider.GetRemarksAsync(interfaceMethod);
}
actionModel.Description = method.GetCustomAttribute<DescriptionAttribute>()?.Description;
actionModel.DisplayName = method.GetCustomAttribute<DisplayAttribute>()?.Name;
actionModel.ReturnValue.Summary = await _xmlDocProvider.GetReturnsAsync(method);
if (actionModel.ReturnValue.Summary == null && interfaceMethod != null)
{
actionModel.ReturnValue.Summary = await _xmlDocProvider.GetReturnsAsync(interfaceMethod);
}
}
protected virtual async Task PopulateParameterDescriptionsAsync(ActionApiDescriptionModel actionModel, MethodInfo method, MethodInfo? interfaceMethod)
{
var methodParameters = method.GetParameters();
foreach (var param in actionModel.ParametersOnMethod)
{
var paramInfo = methodParameters.FirstOrDefault(p => p.Name == param.Name);
if (paramInfo == null)
{
continue;
}
param.Summary = await _xmlDocProvider.GetParameterSummaryAsync(method, param.Name);
if (param.Summary == null && interfaceMethod != null)
{
param.Summary = await _xmlDocProvider.GetParameterSummaryAsync(interfaceMethod, param.Name);
}
param.Description = paramInfo.GetCustomAttribute<DescriptionAttribute>()?.Description;
param.DisplayName = paramInfo.GetCustomAttribute<DisplayAttribute>()?.Name;
}
foreach (var param in actionModel.Parameters)
{
// Skip expanded properties from complex types - their descriptions
// should come from type-level documentation (PopulateTypeDescriptionsAsync)
if (!string.IsNullOrEmpty(param.DescriptorName) && param.Name != param.NameOnMethod)
{
continue;
}
param.Summary = await _xmlDocProvider.GetParameterSummaryAsync(method, param.NameOnMethod);
if (param.Summary == null && interfaceMethod != null)
{
param.Summary = await _xmlDocProvider.GetParameterSummaryAsync(interfaceMethod, param.NameOnMethod);
}
var paramInfo = methodParameters.FirstOrDefault(p => p.Name == param.NameOnMethod);
if (paramInfo != null)
{
param.Description = paramInfo.GetCustomAttribute<DescriptionAttribute>()?.Description;
param.DisplayName = paramInfo.GetCustomAttribute<DisplayAttribute>()?.Name;
}
}
}
private MethodInfo? GetInterfaceMethod(MethodInfo method)
{
var declaringType = method.DeclaringType;
if (declaringType == null || declaringType.IsInterface)
{
return null;
}
foreach (var interfaceType in GetDirectInterfaces(declaringType).Where(i => !_modelOptions.IgnoredInterfaces.Contains(i)))
{
var map = declaringType.GetInterfaceMap(interfaceType);
for (var i = 0; i < map.TargetMethods.Length; i++)
{
if (map.TargetMethods[i] == method)
{
return map.InterfaceMethods[i];
}
}
}
return null;
}
private static IEnumerable<Type> GetDirectInterfaces(Type type)
{
var allInterfaces = type.GetInterfaces();
var baseInterfaces = type.BaseType?.GetInterfaces() ?? Type.EmptyTypes;
return allInterfaces.Except(baseInterfaces);
}
protected virtual async Task PopulateTypeDescriptionsAsync(TypeApiDescriptionModel typeModel, Type type)
{
typeModel.Summary = await _xmlDocProvider.GetSummaryAsync(type);
typeModel.Remarks = await _xmlDocProvider.GetRemarksAsync(type);
typeModel.Description = type.GetCustomAttribute<DescriptionAttribute>()?.Description;
typeModel.DisplayName = type.GetCustomAttribute<DisplayAttribute>()?.Name;
if (typeModel.Properties == null)
{
return;
}
foreach (var propModel in typeModel.Properties)
{
var propInfo = type.GetProperty(propModel.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
if (propInfo == null)
{
continue;
}
propModel.Summary = await _xmlDocProvider.GetSummaryAsync(propInfo);
propModel.Description = propInfo.GetCustomAttribute<DescriptionAttribute>()?.Description;
propModel.DisplayName = propInfo.GetCustomAttribute<DisplayAttribute>()?.Name;
}
}
}

7
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ProxyScripting/AbpServiceProxyScriptController.cs

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Volo.Abp.Auditing;
using Volo.Abp.Http;
@ -29,11 +30,11 @@ public class AbpServiceProxyScriptController : AbpController
[HttpGet]
[Produces(MimeTypes.Application.Javascript, MimeTypes.Text.Plain)]
public virtual ActionResult GetAll(ServiceProxyGenerationModel model)
public virtual async Task<ActionResult> GetAll(ServiceProxyGenerationModel model)
{
model.Normalize();
var script = ProxyScriptManager.GetScript(model.CreateOptions());
var script = await ProxyScriptManager.GetScriptAsync(model.CreateOptions());
return Content(
Options.MinifyGeneratedScript == true

18
framework/src/Volo.Abp.BackgroundJobs.TickerQ/Volo/Abp/BackgroundJobs/TickerQ/AbpBackgroundJobsTickerQModule.cs

@ -23,26 +23,14 @@ public class AbpBackgroundJobsTickerQModule : AbpModule
{
var abpBackgroundJobOptions = context.ServiceProvider.GetRequiredService<IOptions<AbpBackgroundJobOptions>>();
var abpBackgroundJobsTickerQOptions = context.ServiceProvider.GetRequiredService<IOptions<AbpBackgroundJobsTickerQOptions>>();
var tickerFunctionDelegates = new Dictionary<string, (string, TickerTaskPriority, TickerFunctionDelegate)>();
var requestTypes = new Dictionary<string, (string, Type)>();
var abpTickerQFunctionProvider = context.ServiceProvider.GetRequiredService<AbpTickerQFunctionProvider>();
foreach (var jobConfiguration in abpBackgroundJobOptions.Value.GetJobs())
{
var genericMethod = GetTickerFunctionDelegateMethod.MakeGenericMethod(jobConfiguration.ArgsType);
var tickerFunctionDelegate = (TickerFunctionDelegate)genericMethod.Invoke(null, [jobConfiguration.ArgsType])!;
var config = abpBackgroundJobsTickerQOptions.Value.GetConfigurationOrNull(jobConfiguration.JobType);
tickerFunctionDelegates.TryAdd(jobConfiguration.JobName, (string.Empty, config?.Priority ?? TickerTaskPriority.Normal, tickerFunctionDelegate));
requestTypes.TryAdd(jobConfiguration.JobName, (jobConfiguration.ArgsType.FullName, jobConfiguration.ArgsType)!);
}
var abpTickerQFunctionProvider = context.ServiceProvider.GetRequiredService<AbpTickerQFunctionProvider>();
foreach (var functionDelegate in tickerFunctionDelegates)
{
abpTickerQFunctionProvider.Functions.TryAdd(functionDelegate.Key, functionDelegate.Value);
}
foreach (var requestType in requestTypes)
{
abpTickerQFunctionProvider.RequestTypes.TryAdd(requestType.Key, requestType.Value);
abpTickerQFunctionProvider.AddFunction(jobConfiguration.JobName, tickerFunctionDelegate, config?.Priority ?? TickerTaskPriority.Normal, config?.MaxConcurrency ?? 0);
abpTickerQFunctionProvider.RequestTypes.TryAdd(jobConfiguration.JobName, (jobConfiguration.ArgsType.FullName, jobConfiguration.ArgsType)!);
}
}

2
framework/src/Volo.Abp.BackgroundJobs.TickerQ/Volo/Abp/BackgroundJobs/TickerQ/AbpBackgroundJobsTimeTickerConfiguration.cs

@ -10,5 +10,7 @@ public class AbpBackgroundJobsTimeTickerConfiguration
public TickerTaskPriority? Priority { get; set; }
public int? MaxConcurrency { get; set; }
public RunCondition? RunCondition { get; set; }
}

2
framework/src/Volo.Abp.BackgroundWorkers.TickerQ/Volo/Abp/BackgroundWorkers/TickerQ/AbpBackgroundWorkersCronTickerConfiguration.cs

@ -9,4 +9,6 @@ public class AbpBackgroundWorkersCronTickerConfiguration
public int[]? RetryIntervals { get; set; }
public TickerTaskPriority? Priority { get; set; }
public int? MaxConcurrency { get; set; }
}

4
framework/src/Volo.Abp.BackgroundWorkers.TickerQ/Volo/Abp/BackgroundWorkers/TickerQ/AbpTickerQBackgroundWorkerManager.cs

@ -53,11 +53,11 @@ public class AbpTickerQBackgroundWorkerManager : BackgroundWorkerManager, ISingl
var name = BackgroundWorkerNameAttribute.GetNameOrNull(worker.GetType()) ?? worker.GetType().FullName;
var config = Options.GetConfigurationOrNull(ProxyHelper.GetUnProxiedType(worker));
AbpTickerQFunctionProvider.Functions.TryAdd(name!, (string.Empty, config?.Priority ?? TickerTaskPriority.LongRunning, async (tickerQCancellationToken, serviceProvider, tickerFunctionContext) =>
AbpTickerQFunctionProvider.AddFunction(name!, async (tickerQCancellationToken, serviceProvider, tickerFunctionContext) =>
{
var workerInvoker = new AbpTickerQPeriodicBackgroundWorkerInvoker(worker, serviceProvider);
await workerInvoker.DoWorkAsync(tickerFunctionContext, tickerQCancellationToken);
}));
}, config?.Priority ?? TickerTaskPriority.LongRunning, config?.MaxConcurrency ?? 0);
AbpTickerQBackgroundWorkersProvider.BackgroundWorkers.Add(name!, new AbpTickerQCronBackgroundWorker
{

1
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs

@ -80,6 +80,7 @@ public class AbpCliCoreModule : AbpModule
options.Commands[RecreateInitialMigrationCommand.Name] = typeof(RecreateInitialMigrationCommand);
options.Commands[GenerateRazorPage.Name] = typeof(GenerateRazorPage);
options.Commands[McpCommand.Name] = typeof(McpCommand);
options.Commands[GenerateJwksCommand.Name] = typeof(GenerateJwksCommand);
options.DisabledModulesToAddToSolution.Add("Volo.Abp.LeptonXTheme.Pro");
options.DisabledModulesToAddToSolution.Add("Volo.Abp.LeptonXTheme.Lite");

173
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateJwksCommand.cs

@ -0,0 +1,173 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Volo.Abp.Cli.Args;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.Cli.Commands;
public class GenerateJwksCommand : IConsoleCommand, ITransientDependency
{
public const string Name = "generate-jwks";
public ILogger<GenerateJwksCommand> Logger { get; set; }
public GenerateJwksCommand()
{
Logger = NullLogger<GenerateJwksCommand>.Instance;
}
public Task ExecuteAsync(CommandLineArgs commandLineArgs)
{
var outputDir = commandLineArgs.Options.GetOrNull("output", "o")
?? Directory.GetCurrentDirectory();
var keySizeStr = commandLineArgs.Options.GetOrNull("key-size", "s") ?? "2048";
var alg = commandLineArgs.Options.GetOrNull("alg") ?? "RS256";
var kid = commandLineArgs.Options.GetOrNull("kid") ?? Guid.NewGuid().ToString("N");
var filePrefix = commandLineArgs.Options.GetOrNull("file", "f") ?? "jwks";
if (!int.TryParse(keySizeStr, out var keySize) || (keySize != 2048 && keySize != 4096))
{
Logger.LogError("Invalid key size '{0}'. Supported values: 2048, 4096.", keySizeStr);
return Task.CompletedTask;
}
if (!IsValidAlgorithm(alg))
{
Logger.LogError("Invalid algorithm '{0}'. Supported values: RS256, RS384, RS512, PS256, PS384, PS512.", alg);
return Task.CompletedTask;
}
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
Logger.LogInformation("Generating RSA {0}-bit key pair (algorithm: {1})...", keySize, alg);
using var rsa = RSA.Create();
rsa.KeySize = keySize;
var jwksJson = BuildJwksJson(rsa, alg, kid);
var privateKeyPem = ExportPrivateKeyPem(rsa);
var jwksFilePath = Path.Combine(outputDir, $"{filePrefix}.json");
var privateKeyFilePath = Path.Combine(outputDir, $"{filePrefix}-private.pem");
File.WriteAllText(jwksFilePath, jwksJson, Encoding.UTF8);
File.WriteAllText(privateKeyFilePath, privateKeyPem, Encoding.UTF8);
Logger.LogInformation("");
Logger.LogInformation("Generated files:");
Logger.LogInformation(" JWKS (public key) : {0}", jwksFilePath);
Logger.LogInformation(" Private key (PEM) : {0}", privateKeyFilePath);
Logger.LogInformation("");
Logger.LogInformation("JWKS content (paste this into the ABP OpenIddict application's 'JSON Web Key Set' field):");
Logger.LogInformation("");
Logger.LogInformation("{0}", jwksJson);
Logger.LogInformation("");
Logger.LogInformation("IMPORTANT: Keep the private key file safe. Never share it or commit it to source control.");
Logger.LogInformation(" The JWKS file contains only the public key and is safe to share.");
return Task.CompletedTask;
}
private static string BuildJwksJson(RSA rsa, string alg, string kid)
{
var parameters = rsa.ExportParameters(false);
var n = Base64UrlEncode(parameters.Modulus);
var e = Base64UrlEncode(parameters.Exponent);
using var stream = new System.IO.MemoryStream();
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
writer.WriteStartObject();
writer.WriteStartArray("keys");
writer.WriteStartObject();
writer.WriteString("kty", "RSA");
writer.WriteString("use", "sig");
writer.WriteString("kid", kid);
writer.WriteString("alg", alg);
writer.WriteString("n", n);
writer.WriteString("e", e);
writer.WriteEndObject();
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
return Encoding.UTF8.GetString(stream.ToArray());
}
private static string ExportPrivateKeyPem(RSA rsa)
{
#if NET5_0_OR_GREATER
return rsa.ExportPkcs8PrivateKeyPem();
#elif NETSTANDARD2_0
// RSA.ExportPkcs8PrivateKey() was introduced in .NET Standard 2.1.
// The ABP CLI always runs on .NET 5+, so this path is never reached at runtime.
throw new PlatformNotSupportedException("Private key export requires .NET Standard 2.1 or later.");
#else
var privateKeyBytes = rsa.ExportPkcs8PrivateKey();
var base64 = Convert.ToBase64String(privateKeyBytes, Base64FormattingOptions.InsertLineBreaks);
return $"-----BEGIN PRIVATE KEY-----\n{base64}\n-----END PRIVATE KEY-----";
#endif
}
private static string Base64UrlEncode(byte[] input)
{
return Convert.ToBase64String(input)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
private static bool IsValidAlgorithm(string alg)
{
return alg == "RS256" || alg == "RS384" || alg == "RS512" ||
alg == "PS256" || alg == "PS384" || alg == "PS512";
}
public string GetUsageInfo()
{
var sb = new StringBuilder();
sb.AppendLine("");
sb.AppendLine("Usage:");
sb.AppendLine(" abp generate-jwks [options]");
sb.AppendLine("");
sb.AppendLine("Options:");
sb.AppendLine(" -o|--output <dir> Output directory (default: current directory)");
sb.AppendLine(" -s|--key-size <size> RSA key size: 2048 or 4096 (default: 2048)");
sb.AppendLine(" --alg <alg> Algorithm: RS256, RS384, RS512, PS256, PS384, PS512 (default: RS256)");
sb.AppendLine(" --kid <id> Key ID (kid) - auto-generated if not specified");
sb.AppendLine(" -f|--file <prefix> Output file name prefix (default: jwks)");
sb.AppendLine(" Generates: <prefix>.json (JWKS) and <prefix>-private.pem (private key)");
sb.AppendLine("");
sb.AppendLine("Examples:");
sb.AppendLine(" abp generate-jwks");
sb.AppendLine(" abp generate-jwks --alg RS512 --key-size 4096");
sb.AppendLine(" abp generate-jwks -o ./keys -f myapp");
sb.AppendLine("");
sb.AppendLine("Description:");
sb.AppendLine(" Generates an RSA key pair for use with OpenIddict private_key_jwt client authentication.");
sb.AppendLine(" The JWKS file (public key) should be pasted into the ABP OpenIddict application's");
sb.AppendLine(" 'JSON Web Key Set' field in the management UI.");
sb.AppendLine(" The private key PEM file should be kept secure and used by the client application");
sb.AppendLine(" to sign JWT assertions when authenticating to the token endpoint.");
sb.AppendLine("");
sb.AppendLine("See the documentation for more info: https://abp.io/docs/latest/cli");
return sb.ToString();
}
public static string GetShortDescription()
{
return "Generates an RSA key pair (JWKS + private key) for OpenIddict private_key_jwt authentication.";
}
}

74
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/EntityCacheBase.cs

@ -1,4 +1,6 @@
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Caching;
using Volo.Abp.Data;
using Volo.Abp.Domain.Entities.Events;
@ -44,6 +46,20 @@ public abstract class EntityCacheBase<TEntity, TEntityCacheItem, TKey> :
}))?.Value;
}
public virtual async Task<List<TEntityCacheItem?>> FindManyAsync(IEnumerable<TKey> ids)
{
var idArray = ids.ToArray();
var distinctIds = idArray.Distinct().ToArray();
var cacheItems = await GetOrAddManyCacheItemsAsync(distinctIds);
#pragma warning disable CS8714
var cacheItemDict = cacheItems.ToDictionary(x => x.Key, x => x.Value);
#pragma warning restore CS8714
return idArray
.Select(id => cacheItemDict.TryGetValue(id!, out var wrapper) ? wrapper?.Value : null)
.ToList();
}
public virtual async Task<TEntityCacheItem> GetAsync(TKey id)
{
return (await Cache.GetOrAddAsync(
@ -59,6 +75,62 @@ public abstract class EntityCacheBase<TEntity, TEntityCacheItem, TKey> :
}))!.Value!;
}
public virtual async Task<List<TEntityCacheItem>> GetManyAsync(IEnumerable<TKey> ids)
{
var idArray = ids.ToArray();
var distinctIds = idArray.Distinct().ToArray();
var cacheItems = await GetOrAddManyCacheItemsAsync(distinctIds);
#pragma warning disable CS8714
var cacheItemDict = cacheItems.ToDictionary(x => x.Key, x => x.Value);
#pragma warning restore CS8714
return idArray
.Select(id =>
{
var cacheItem = cacheItemDict.TryGetValue(id!, out var wrapper) ? wrapper?.Value : null;
if (cacheItem == null)
{
throw new EntityNotFoundException<TEntity>(id);
}
return cacheItem;
})
.ToList();
}
protected virtual async Task<KeyValuePair<TKey, EntityCacheItemWrapper<TEntityCacheItem>?>[]> GetOrAddManyCacheItemsAsync(TKey[] ids)
{
return await Cache.GetOrAddManyAsync(
ids,
async missingKeys =>
{
if (HasObjectExtensionInfo())
{
Repository.EnableTracking();
}
var missingKeyArray = missingKeys.ToArray();
var entities = await Repository.GetListAsync(
x => missingKeyArray.Contains(x.Id),
includeDetails: true
);
#pragma warning disable CS8714
var entityDict = entities.ToDictionary(e => e.Id);
#pragma warning restore CS8714
return missingKeyArray
.Select(key =>
{
entityDict.TryGetValue(key!, out var entity);
return new KeyValuePair<TKey, EntityCacheItemWrapper<TEntityCacheItem>>(
key,
MapToCacheItem(entity)!
);
})
.ToList();
});
}
protected virtual bool HasObjectExtensionInfo()
{
return typeof(IHasExtraProperties).IsAssignableFrom(typeof(TEntity)) &&

26
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/EntityCacheServiceCollectionExtensions.cs

@ -65,6 +65,32 @@ public static class EntityCacheServiceCollectionExtensions
return services;
}
public static IServiceCollection ReplaceEntityCache<TEntityCache, TEntity, TEntityCacheItem, TKey>(
this IServiceCollection services,
DistributedCacheEntryOptions? cacheOptions = null)
where TEntityCache : EntityCacheBase<TEntity, TEntityCacheItem, TKey>
where TEntity : Entity<TKey>
where TEntityCacheItem : class
{
services.Replace(ServiceDescriptor.Transient<IEntityCache<TEntityCacheItem, TKey>, TEntityCache>());
services.TryAddTransient<TEntityCache>();
services.Configure<AbpDistributedCacheOptions>(options =>
{
options.ConfigureCache<EntityCacheItemWrapper<TEntityCacheItem>>(cacheOptions ?? GetDefaultCacheOptions());
});
if (typeof(TEntity) == typeof(TEntityCacheItem))
{
services.Configure<AbpSystemTextJsonSerializerModifiersOptions>(options =>
{
options.Modifiers.Add(new AbpIncludeNonPublicPropertiesModifiers<TEntity, TKey>().CreateModifyAction(x => x.Id));
});
}
return services;
}
private static DistributedCacheEntryOptions GetDefaultCacheOptions()
{
return new DistributedCacheEntryOptions {

9
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/EntityCacheWithObjectMapper.cs

@ -30,11 +30,16 @@ public class EntityCacheWithObjectMapper<TEntity, TEntityCacheItem, TKey> :
return null;
}
return new EntityCacheItemWrapper<TEntityCacheItem>(MapToValue(entity));
}
protected virtual TEntityCacheItem MapToValue(TEntity entity)
{
if (typeof(TEntity) == typeof(TEntityCacheItem))
{
return new EntityCacheItemWrapper<TEntityCacheItem>(entity.As<TEntityCacheItem>());
return entity.As<TEntityCacheItem>();
}
return new EntityCacheItemWrapper<TEntityCacheItem>(ObjectMapper.Map<TEntity, TEntityCacheItem>(entity));
return ObjectMapper.Map<TEntity, TEntityCacheItem>(entity);
}
}

21
framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/Caching/IEntityCache.cs

@ -1,4 +1,5 @@
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Volo.Abp.Domain.Entities.Caching;
@ -11,11 +12,25 @@ public interface IEntityCache<TEntityCacheItem, in TKey>
/// or returns null if the entity was not found.
/// </summary>
Task<TEntityCacheItem?> FindAsync(TKey id);
/// <summary>
/// Gets multiple entities with the given <paramref name="ids"/>.
/// Returns a list where each entry corresponds to the given id in the same order.
/// An entry will be null if the entity was not found for the corresponding id.
/// </summary>
Task<List<TEntityCacheItem?>> FindManyAsync(IEnumerable<TKey> ids);
/// <summary>
/// Gets the entity with given <paramref name="id"/>,
/// or throws <see cref="EntityNotFoundException"/> if the entity was not found.
/// </summary>
[ItemNotNull]
Task<TEntityCacheItem> GetAsync(TKey id);
}
/// <summary>
/// Gets multiple entities with the given <paramref name="ids"/>.
/// Returns a list where each entry corresponds to the given id in the same order.
/// Throws <see cref="EntityNotFoundException"/> if any entity was not found.
/// </summary>
Task<List<TEntityCacheItem>> GetManyAsync(IEnumerable<TKey> ids);
}

8
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ActionApiDescriptionModel.cs

@ -32,6 +32,14 @@ public class ActionApiDescriptionModel
public string? ImplementFrom { get; set; }
public string? Summary { get; set; }
public string? Remarks { get; set; }
public string? Description { get; set; }
public string? DisplayName { get; set; }
public ActionApiDescriptionModel()
{

2
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ApplicationApiDescriptionModelRequestDto.cs

@ -3,4 +3,6 @@
public class ApplicationApiDescriptionModelRequestDto
{
public bool IncludeTypes { get; set; }
public bool IncludeDescriptions { get; set; }
}

16
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ControllerApiDescriptionModel.cs

@ -19,6 +19,14 @@ public class ControllerApiDescriptionModel
public string Type { get; set; } = default!;
public string? Summary { get; set; }
public string? Remarks { get; set; }
public string? Description { get; set; }
public string? DisplayName { get; set; }
public List<ControllerInterfaceApiDescriptionModel> Interfaces { get; set; } = default!;
public Dictionary<string, ActionApiDescriptionModel> Actions { get; set; } = default!;
@ -66,6 +74,14 @@ public class ControllerApiDescriptionModel
Type = Type,
Interfaces = Interfaces,
ControllerName = ControllerName,
ControllerGroupName = ControllerGroupName,
IsRemoteService = IsRemoteService,
IsIntegrationService = IsIntegrationService,
ApiVersion = ApiVersion,
Summary = Summary,
Remarks = Remarks,
Description = Description,
DisplayName = DisplayName,
Actions = new Dictionary<string, ActionApiDescriptionModel>()
};

4
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/IApiDescriptionModelProvider.cs

@ -1,6 +1,8 @@
using System.Threading.Tasks;
namespace Volo.Abp.Http.Modeling;
public interface IApiDescriptionModelProvider
{
ApplicationApiDescriptionModel CreateApiModel(ApplicationApiDescriptionModelRequestDto input);
Task<ApplicationApiDescriptionModel> CreateApiModelAsync(ApplicationApiDescriptionModelRequestDto input);
}

6
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/MethodParameterApiDescriptionModel.cs

@ -19,6 +19,12 @@ public class MethodParameterApiDescriptionModel
public object? DefaultValue { get; set; }
public string? Summary { get; set; }
public string? Description { get; set; }
public string? DisplayName { get; set; }
public MethodParameterApiDescriptionModel()
{

6
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ParameterApiDescriptionModel.cs

@ -26,6 +26,12 @@ public class ParameterApiDescriptionModel
public string? DescriptorName { get; set; }
public string? Summary { get; set; }
public string? Description { get; set; }
public string? DisplayName { get; set; }
public ParameterApiDescriptionModel()
{

6
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/PropertyApiDescriptionModel.cs

@ -32,6 +32,12 @@ public class PropertyApiDescriptionModel
public bool IsNullable { get; set; }
public string? Summary { get; set; }
public string? Description { get; set; }
public string? DisplayName { get; set; }
public static PropertyApiDescriptionModel Create(PropertyInfo propertyInfo)
{
var customAttributes = propertyInfo.GetCustomAttributes(true);

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save