Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
246bb4c33d | ||
|
|
ac811c2624 |
@@ -1,94 +0,0 @@
|
||||
---
|
||||
name: umb-bump-version
|
||||
description: Bump the Umbraco CMS version across all required files. Use when the user asks to bump, update, or set the version number — e.g., "bump version to 17.3.4", "set version to 18.0.0-rc", "update version". Accepts the target version as an argument.
|
||||
argument-hint: <version> (e.g., 17.3.4, 18.0.0-rc)
|
||||
---
|
||||
|
||||
# Bump Version - Umbraco CMS
|
||||
|
||||
Updates the Umbraco CMS version string across all files that track it.
|
||||
|
||||
**Do NOT use AskUserQuestion if a version argument is provided. Only ask if `$ARGUMENTS` is empty or cannot be parsed as a version.**
|
||||
|
||||
## Arguments
|
||||
|
||||
- `$ARGUMENTS` - Required: the target version string (e.g., `17.3.4`, `18.0.0-rc`)
|
||||
|
||||
## Files to Update
|
||||
|
||||
The following 5 files must be updated with the new version:
|
||||
|
||||
| # | File | Field |
|
||||
|---|------|-------|
|
||||
| 1 | `version.json` | `"version"` |
|
||||
| 2 | `src/Umbraco.Web.UI.Client/package.json` | `"version"` |
|
||||
| 3 | `src/Umbraco.Web.UI.Client/package-lock.json` | top-level `"version"` AND `packages[""].version` |
|
||||
| 4 | `tests/Umbraco.Tests.AcceptanceTest/package.json` | `"version"` |
|
||||
| 5 | `tests/Umbraco.Tests.AcceptanceTest/package-lock.json` | top-level `"version"` AND `packages[""].version` |
|
||||
|
||||
**Note**: For major version bumps (e.g., 17.x to 18.x), `src/Umbraco.Web.UI.Login/package.json` has a caret-ranged dependency on `@umbraco-cms/backoffice` (e.g., `^17.2.0`) that will need manual updating. This skill does not handle that — major bumps involve many other changes beyond version strings.
|
||||
|
||||
## Instructions
|
||||
|
||||
### 1. Parse and Validate the Version
|
||||
|
||||
Extract the version from `$ARGUMENTS`. It must be a valid semver-like string (e.g., `17.3.4`, `18.0.0-rc`, `17.4.0-preview.1`). If no version is provided or it cannot be parsed, ask the user for the target version.
|
||||
|
||||
### 2. Read the Current Version
|
||||
|
||||
Read `version.json` and extract the current `"version"` value. If the current version already equals the target version, report that the version is already set and stop — do not edit, stage, or commit anything.
|
||||
|
||||
Otherwise, display both versions:
|
||||
|
||||
```
|
||||
Bumping version: {current} -> {target}
|
||||
```
|
||||
|
||||
### 3. Update All Files
|
||||
|
||||
Update each of the 5 files listed above, replacing the old version with the new version. For each file:
|
||||
|
||||
- **`version.json`**: Replace the `"version"` value.
|
||||
- **`package.json` files**: Replace the `"version"` value (near the top of the file).
|
||||
- **`package-lock.json` files**: Replace BOTH the top-level `"version"` value AND the `"version"` inside the `"packages": { "": { ... } }` block. These are always in the first ~10 lines of the file.
|
||||
|
||||
Use targeted edits — do NOT rewrite entire files. Be precise to avoid changing version strings in dependency entries.
|
||||
|
||||
### 4. Verify
|
||||
|
||||
After all edits, grep for the target version value across the 5 files to confirm all updates landed correctly:
|
||||
|
||||
```bash
|
||||
grep -n "\"version\": \"{version}\"" version.json src/Umbraco.Web.UI.Client/package.json src/Umbraco.Web.UI.Client/package-lock.json tests/Umbraco.Tests.AcceptanceTest/package.json tests/Umbraco.Tests.AcceptanceTest/package-lock.json
|
||||
```
|
||||
|
||||
Expect exactly 7 matches (one per `package.json` and `version.json`, two per `package-lock.json`).
|
||||
|
||||
### 5. Stage and Commit
|
||||
|
||||
Stage only the 5 changed files:
|
||||
|
||||
```bash
|
||||
git add version.json src/Umbraco.Web.UI.Client/package.json src/Umbraco.Web.UI.Client/package-lock.json tests/Umbraco.Tests.AcceptanceTest/package.json tests/Umbraco.Tests.AcceptanceTest/package-lock.json
|
||||
```
|
||||
|
||||
Then commit with the message `Bump version to {version}.` — replacing `{version}` with the target version:
|
||||
|
||||
```bash
|
||||
git commit -m "Bump version to {version}."
|
||||
```
|
||||
|
||||
### 6. Report
|
||||
|
||||
Output a summary:
|
||||
|
||||
```
|
||||
Version bumped to {version} in:
|
||||
- version.json
|
||||
- src/Umbraco.Web.UI.Client/package.json
|
||||
- src/Umbraco.Web.UI.Client/package-lock.json
|
||||
- tests/Umbraco.Tests.AcceptanceTest/package.json
|
||||
- tests/Umbraco.Tests.AcceptanceTest/package-lock.json
|
||||
|
||||
Changes staged and committed.
|
||||
```
|
||||
@@ -1,135 +0,0 @@
|
||||
---
|
||||
name: umb-release-notes
|
||||
description: Improve a set of auto-generated GitHub release notes for an Umbraco CMS release. Cross-checks the notes against every PR carrying the release label, adds any that are missing, re-files every PR under the most appropriate category, and strips purely-internal entries. Use whenever the user asks to tidy up, improve, complete, or recategorize release notes for a given version, or mentions a release-notes text file plus a version number.
|
||||
argument-hint: <version> <path-to-generated-notes-file>
|
||||
---
|
||||
|
||||
# Umbraco CMS - Improve Release Notes
|
||||
|
||||
Takes a file of auto-generated GitHub release notes and produces an improved version that:
|
||||
|
||||
1. **Is complete** — every merged PR carrying the `release/<version>` label appears.
|
||||
2. **Is well-categorized** — every PR sits under the most appropriate heading.
|
||||
3. **Is free of noise** — purely-internal entries of no value to a reader are removed.
|
||||
|
||||
The result is written to a **new** file alongside the input, so the user can diff the two.
|
||||
|
||||
**Run autonomously.** Do NOT use `AskUserQuestion` once the required arguments (version and input file path) are available — only ask if one of them is missing from `$ARGUMENTS` and cannot be inferred (see Arguments). Beyond that, make the categorization calls yourself using the rules below; if a handful are genuinely borderline, place them anyway and note the borderline ones in your closing summary so the user can override.
|
||||
|
||||
## Arguments
|
||||
|
||||
`$ARGUMENTS` contains two values:
|
||||
|
||||
1. **Version** — e.g. `17.5.0`, `18.1.0`. The GitHub label to search is `release/<version>` (so version `17.5.0` → label `release/17.5.0`).
|
||||
2. **Input file path** — full path to the text file holding the auto-generated notes (e.g. `C:\Temp\release-17.5.0-rc.md`).
|
||||
|
||||
If either is missing, ask the user once for the missing value, then proceed.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Run `gh auth status`. If it fails, tell the user to authenticate `gh` (e.g. `gh auth login`) and stop — the skill needs the GitHub CLI to query PRs. The repo is always `umbraco/Umbraco-CMS`.
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Read the input notes
|
||||
|
||||
Read the input file. Note its structure — it is GitHub's generated format:
|
||||
|
||||
- A leading HTML comment (`<!-- Release notes generated ... -->`).
|
||||
- A `## What's Changed` heading followed by `### <emoji> <Category>` sub-headings, each with `* <title> by @<author> in <url>` bullets.
|
||||
- A trailing `## New Contributors` section and a `**Full Changelog**: ...` line.
|
||||
|
||||
Extract the set of PR numbers already present (parse the `/pull/<number>` from each bullet). Preserve each existing bullet's **exact text** (title, author, URL) when you re-emit it — only its category placement may change.
|
||||
|
||||
### 2. Fetch every labelled PR
|
||||
|
||||
```bash
|
||||
gh pr list --repo umbraco/Umbraco-CMS --label "release/<version>" --state closed --limit 1000 \
|
||||
--json number,title,author,labels,mergedAt \
|
||||
--jq '.[] | select(.mergedAt != null) | "\(.number)\t\(.author.login)\t\([.labels[].name] | join(", "))\t\(.title)"' | sort -n
|
||||
```
|
||||
|
||||
This is the authoritative list of what the release *should* contain. Each row gives number, author, labels, title.
|
||||
|
||||
**Guard against silent truncation.** `gh pr list` caps at `--limit` without warning, so a large release could drop the overflow and the skill would still look "complete". Count the returned rows and compare against the limit:
|
||||
|
||||
```bash
|
||||
gh pr list --repo umbraco/Umbraco-CMS --label "release/<version>" --state closed --limit 1000 --json number --jq 'length'
|
||||
```
|
||||
|
||||
If this equals 1000, the limit was hit — raise `--limit` and re-fetch before continuing. Do **not** proceed on a truncated list.
|
||||
|
||||
### 3. Reconcile
|
||||
|
||||
- **Missing labelled PRs** (labelled but not in the input file): these must be **added**. Build a bullet as `* <title> by @<author> in https://github.com/umbraco/Umbraco-CMS/pull/<number>`.
|
||||
- **Author handle.** `<author>` in the template is the raw `.author.login` value — the bullet supplies the leading `@`, so do not prepend another. `gh`'s `.author.login` already returns bot accounts with the `[bot]` suffix as part of the login — Dependabot comes back as `dependabot[bot]`, not `dependabot` or `app/dependabot` (the `app/` form only appears in git committer metadata and CODEOWNERS, never in `gh`'s JSON). So the login is already in the right shape; use it verbatim (e.g. `.author.login` of `dependabot[bot]` renders as `@dependabot[bot]`, matching what GitHub's generator wrote for the existing bullets). The only thing to guard against is accidentally stripping or altering the `[bot]` suffix.
|
||||
- **PRs in the file but not labelled**: keep them. The generated notes span a commit range (see the `Full Changelog` compare link), so they legitimately include backports / earlier-version PRs that lack the current label. For any of these you need to categorize, fetch its labels with:
|
||||
|
||||
```bash
|
||||
gh pr view <number> --repo umbraco/Umbraco-CMS --json number,title,labels \
|
||||
--jq '"\(.number)\t\([.labels[].name] | join(", "))\t\(.title)"'
|
||||
```
|
||||
|
||||
Do **not** invent or alter the `New Contributors` section — carry it over verbatim. You cannot reliably recompute first-time contributors, so leave it as the generator produced it (mention this in the summary).
|
||||
|
||||
### 4. Categorize every PR
|
||||
|
||||
Use exactly these headings, in this order. Omit any heading that ends up with no entries.
|
||||
|
||||
| Heading | What goes here | Primary signal |
|
||||
|---|---|---|
|
||||
| `### 🙌 Notable Changes` | **Don't recategorize existing entries.** Label-driven — but still add any missing PR carrying this label here. | label `category/notable` |
|
||||
| `### 💥 Breaking Changes` | **Don't recategorize existing entries.** Label-driven — but still add any missing PR carrying this label here. | label `category/breaking` |
|
||||
| `### 📦 Dependencies` | Dependency bumps | label `dependencies`; or dependabot author |
|
||||
| `### 🚀 New Features` | New user- or developer-facing capability | label `type/feature` / `category/feature`; or title introduces/adds a genuinely new capability |
|
||||
| `### 🚤 Performance` | Performance improvements | label `category/performance`; or `Performance:` title prefix |
|
||||
| `### 🌈 Accessibility Improvements` | A11y improvements (labels, contrast, keyboard) | label `category/accessibility` / `accessibility`; or clear a11y intent (e.g. "improve contrast", "missing labels") |
|
||||
| `### 🐛 Bug Fixes` | Fixes to broken/incorrect behaviour | default for anything describing a fix |
|
||||
| `### 🧪 Testing` | Test additions/changes only | label `category/test-automation` / `area/test`; or `E2E`/`QA`/"acceptance tests"/"unit test coverage"/"add tests" titles |
|
||||
| `### 🛡️ Code Quality, Documentation and Refactoring` | Refactors, deprecations, API tidy-ups, XML/MD documentation, knowledge-base (`MD`) updates | label `category/refactor`; or titles about refactoring, deprecating, renaming, documenting, constants extraction, MD/CLAUDE.md content |
|
||||
| `### 🧑💻 Developer Experience` | Things that improve the experience of developers building on or contributing to Umbraco — dev tooling, build/watch ergonomics, test mocks/harnesses, backoffice dev utilities | `Developer Experience` title prefix; dev tooling; mock/harness changes |
|
||||
|
||||
**Rules:**
|
||||
|
||||
- **Notable and Breaking are off-limits for recategorization** — never move a PR that is *already in the input file* into or out of these sections; they are driven purely by their labels and the generator placed them correctly. This does **not** exempt them from completeness: a PR discovered as missing in step 3 that carries `category/notable` or `category/breaking` must still be **added** under the matching section.
|
||||
- Label signals beat title wording, except a `Performance:`/`Developer Experience:` title prefix is decisive for its section.
|
||||
- A PR with both `type/feature` and `category/refactor` whose title clearly describes a refactor (e.g. "swap relative imports", "re-export type") belongs under Code Quality, not New Features.
|
||||
- "Add ... tests"/"unit test coverage" → Testing, even if it also touches docs. If a PR adds XML documentation *and* tests, lead with where the title's emphasis lies (documentation → Code Quality; test coverage → Testing).
|
||||
- When a PR is genuinely 50/50, pick the more reader-useful heading and list it in your closing summary as borderline.
|
||||
|
||||
### 5. Remove purely-internal noise
|
||||
|
||||
Drop entries that have **no value to anyone reading release notes** — pure repository plumbing with no shipped impact. Examples:
|
||||
|
||||
- Branch/merge maintenance ("Fix main branch after merge issue").
|
||||
- CI/pipeline fixes that don't change the product.
|
||||
- Reverts of changes that never shipped in a release.
|
||||
|
||||
**Keep** anything that ships in the product or genuinely helps developers building on Umbraco — that includes documentation/MD updates, dev tooling, and test mocks (those go to Code Quality or Developer Experience, they are *not* noise). When unsure whether something is noise, keep it and flag it in the summary rather than silently dropping it. List every removal in your closing summary.
|
||||
|
||||
### 6. Write the output
|
||||
|
||||
Write to a new file in the **same folder** as the input, named by appending ` - with updates` before the extension:
|
||||
|
||||
- Input `C:\Temp\release-17.5.0-rc.md` → Output `C:\Temp\release-17.5.0-rc - with updates.md`
|
||||
|
||||
Preserve the leading HTML comment, the `## What's Changed` heading, the `## New Contributors` section, and the `**Full Changelog**` line exactly. Only the `### <category>` groupings and their bullets change.
|
||||
|
||||
### 7. Report
|
||||
|
||||
Give a concise summary:
|
||||
|
||||
- Count of PRs added (with their numbers), and which categories they landed in.
|
||||
- Notable recategorizations (PRs moved out of the catch-all Bug Fixes into Features/Performance/Testing/etc.).
|
||||
- Every entry removed, with the one-line reason.
|
||||
- Any borderline calls the user may want to override.
|
||||
- The output file path.
|
||||
|
||||
## Verification
|
||||
|
||||
Before reporting done, confirm:
|
||||
|
||||
- Every PR number from step 2 is present in the output (except any you deliberately removed in step 5 — and those must be in the removal list).
|
||||
- No PR appears under more than one heading.
|
||||
- Notable and Breaking sections are byte-for-byte unchanged from the input.
|
||||
- The header comment, New Contributors, and Full Changelog lines are intact.
|
||||
+12
-4
@@ -70,6 +70,18 @@ trim_trailing_whitespace = true
|
||||
[*.less]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
##########################################
|
||||
# File Header (Uncomment to support file headers)
|
||||
# https://docs.microsoft.com/visualstudio/ide/reference/add-file-header
|
||||
##########################################
|
||||
|
||||
# [*.{cs,csx,cake,vb,vbx}]
|
||||
file_header_template = Copyright (c) Umbraco.\nSee LICENSE for more details.
|
||||
|
||||
# SA1636: File header copyright text should match
|
||||
# Justification: .editorconfig supports file headers. If this is changed to a value other than "none", a stylecop.json file will need to added to the project.
|
||||
# dotnet_diagnostic.SA1636.severity = none
|
||||
|
||||
##########################################
|
||||
# .NET Language Conventions
|
||||
# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions
|
||||
@@ -124,10 +136,6 @@ dotnet_code_quality_unused_parameters = all:warning
|
||||
dotnet_style_operator_placement_when_wrapping = end_of_line
|
||||
# https://github.com/dotnet/roslyn/pull/40070
|
||||
dotnet_style_prefer_simplified_interpolation = true:warning
|
||||
# File header preferences
|
||||
file_header_template = Copyright (c) Umbraco.\nSee LICENSE for more details.
|
||||
dotnet_diagnostic.SA1633.severity = none # Suppressed until we decide to enforce it
|
||||
dotnet_diagnostic.SA1636.severity = none # Suppressed since we are using StyleCop
|
||||
|
||||
# C# Code Style Settings
|
||||
# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#c-code-style-settings
|
||||
|
||||
@@ -59,5 +59,4 @@
|
||||
# Generated files - hidden by default in GitHub diffs
|
||||
src/Umbraco.Web.UI.Client/src/packages/core/backend-api/** linguist-generated
|
||||
src/Umbraco.Web.UI.Login/src/api/** linguist-generated
|
||||
templates/UmbracoExtension/Client/src/api/** linguist-generated
|
||||
src/Umbraco.Cms.Api.Management/OpenApi.json linguist-generated
|
||||
|
||||
@@ -7,7 +7,7 @@ body:
|
||||
id: "version"
|
||||
attributes:
|
||||
label: "Which Umbraco version are you using?"
|
||||
description: "Please write the *exact* version, example: `10.1.0`. Click the Umbraco logo in the top left corner of the backoffice to find the version you're using."
|
||||
description: "Please write the *exact* version, example: `10.1.0`. Use the help icon in the Umbraco backoffice to find the version you're using"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Build and Deploy Job
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- name: Build And Deploy
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Build and Deploy Job
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build And Deploy
|
||||
id: builddeploy
|
||||
uses: Azure/static-web-apps-deploy@v1
|
||||
|
||||
@@ -1,52 +1,28 @@
|
||||
name: Claude PR Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review, reopened]
|
||||
# NOTE: `pull_request_target` would let this workflow review fork PRs
|
||||
# (with access to secrets), but the action currently fails during OIDC
|
||||
# token exchange with "401 Unauthorized - Invalid OIDC token" on that
|
||||
# event. PR #579 added `pull_request_target` routing to the action, but
|
||||
# Anthropic's `/github-app-token-exchange` endpoint appears not to
|
||||
# accept the token claims produced by that event. Re-enable once the
|
||||
# upstream issue is resolved.
|
||||
# See: https://github.com/anthropics/claude-code-action/issues/347
|
||||
# https://github.com/anthropics/claude-code-action/issues/621
|
||||
# pull_request_target:
|
||||
# types: [opened, ready_for_review]
|
||||
pull_request_target:
|
||||
types: [opened, ready_for_review]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
id-token: write
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
review:
|
||||
# Skip fork PRs: secrets are not exposed on `pull_request` events from
|
||||
# forks, so the action would fail with a red check. Remove this clause
|
||||
# once upstream fork support lands (tracked in
|
||||
# https://github.com/anthropics/claude-code-action/issues/939) and we
|
||||
# can re-enable the `pull_request_target` trigger above.
|
||||
if: >-
|
||||
github.event.pull_request.draft == false
|
||||
&& github.event.pull_request.head.repo.full_name == github.repository
|
||||
if: github.event.pull_request.draft == false
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY_03 }}
|
||||
|
||||
# Enable progress tracking
|
||||
track_progress: true
|
||||
|
||||
# Debug (set to true to show full output in logs, false to hide it and only post comments on the PR)
|
||||
show_full_output: false
|
||||
|
||||
base_branch: "main"
|
||||
additional_permissions: "actions: read"
|
||||
claude_args: "--model claude-sonnet-4-6 --allowedTools 'Bash(gh:*),Bash(git:*)'"
|
||||
prompt: |
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# We use the setup-dotnet action to set up .NET Core, otherwise the CodeQL CLI will not work with preview versions.
|
||||
- name: Setup .NET from global.json
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
name: Issue Deduplication
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [ opened ]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
issue_number:
|
||||
description: 'Issue number to analyze for duplicates'
|
||||
required: true
|
||||
type: number
|
||||
|
||||
jobs:
|
||||
deduplicate:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Check for duplicate issues
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
prompt: |
|
||||
Analyze this new issue and check if it's a duplicate of existing issues in the repository.
|
||||
|
||||
Issue: #${{ github.event.issue.number || inputs.issue_number }}
|
||||
Repository: ${{ github.repository }}
|
||||
|
||||
Your task:
|
||||
1. Use mcp__github__get_issue to get details of the current issue (#${{ github.event.issue.number || inputs.issue_number }})
|
||||
2. Search for similar existing issues using mcp__github__search_issues with relevant keywords from the issue title and body
|
||||
3. Compare the new issue with existing ones to identify potential duplicates
|
||||
|
||||
Criteria for duplicates:
|
||||
- Same bug or error being reported
|
||||
- Same feature request (even if worded differently)
|
||||
- Same question being asked
|
||||
- Issues describing the same root problem
|
||||
|
||||
If you find duplicates:
|
||||
- Add a comment on the new issue linking to the original issue(s)
|
||||
- Apply the "duplicate" and "state/needs-investigation" labels to the new issue
|
||||
- Be polite and explain why it's a duplicate
|
||||
- Suggest the user follow the original issue for updates
|
||||
|
||||
If it's NOT a duplicate:
|
||||
- Don't add any comments
|
||||
- You may apply appropriate topic labels based on the issue content
|
||||
|
||||
Use these tools:
|
||||
- mcp__github__get_issue: Get issue details
|
||||
- mcp__github__search_issues: Search for similar issues
|
||||
- mcp__github__list_issues: List recent issues if needed
|
||||
- mcp__github__add_issue_comment: Add a comment if duplicate found
|
||||
- mcp__github__update_issue: Add labels
|
||||
|
||||
Be thorough but efficient. Focus on finding true duplicates, not just similar issues.
|
||||
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY_03 }}
|
||||
|
||||
# Issues are opened by community members without write access, so the
|
||||
# default OIDC token exchange fails with "User does not have write
|
||||
# access on this repository". Pass `github_token` explicitly and set
|
||||
# `allowed_non_write_users` to bypass that check. Safe here because
|
||||
# `permissions:` and `--allowedTools` below are tightly scoped to
|
||||
# issue operations only.
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
allowed_non_write_users: "*"
|
||||
|
||||
# Surface full SDK output (including tool calls and permission denials)
|
||||
# to diagnose why Claude sometimes only partially completes (e.g. labels
|
||||
# an issue but skips the comment). Safe to leave on — no secrets in output.
|
||||
show_full_output: true
|
||||
|
||||
claude_args: |
|
||||
--model claude-haiku-4-5 --allowedTools "mcp__github__get_issue,mcp__github__search_issues,mcp__github__list_issues,mcp__github__add_issue_comment,mcp__github__update_issue,mcp__github__get_issue_comments"
|
||||
@@ -1,99 +0,0 @@
|
||||
name: "SonarQube Cloud - Analysis"
|
||||
|
||||
# This workflow runs the full SonarCloud analysis with the SONAR_TOKEN secret.
|
||||
# It is skipped for fork PRs since secrets are not available in that context.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- "v*/dev"
|
||||
- "v*/main"
|
||||
- "release/*"
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
SONAR_PROJECT_KEY: umbraco_Umbraco-CMS
|
||||
SONAR_ORGANIZATION: umbraco
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Build and analyze
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork != true
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup .NET from global.json
|
||||
uses: actions/setup-dotnet@v5
|
||||
|
||||
- name: Setup Java 21
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
|
||||
- name: Cache SonarQube packages
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.sonar/cache
|
||||
key: ${{ runner.os }}-sonar
|
||||
restore-keys: ${{ runner.os }}-sonar
|
||||
|
||||
- name: Install tools
|
||||
run: |
|
||||
dotnet tool install --global dotnet-sonarscanner
|
||||
dotnet tool install --global dotnet-coverage
|
||||
|
||||
- name: Load sonar params
|
||||
run: echo "SONARQUBE_SCANNER_PARAMS=$(jq -c . .github/workflows/sonarcloud/sonar-params.json)" >> $GITHUB_ENV
|
||||
|
||||
- name: Begin analysis
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
dotnet-sonarscanner begin \
|
||||
/k:"$SONAR_PROJECT_KEY" \
|
||||
/o:"$SONAR_ORGANIZATION" \
|
||||
/d:sonar.token="$SONAR_TOKEN" \
|
||||
/d:sonar.scanner.skipJreProvisioning=true
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore umbraco.sln
|
||||
|
||||
- name: Build solution
|
||||
run: GITHUB_ENV=/dev/null dotnet build umbraco.sln --no-restore -clp:ErrorsOnly # prevent sonar MSBuild integration from writing malformed values to $GITHUB_ENV
|
||||
|
||||
- name: Run unit tests with coverage
|
||||
id: tests
|
||||
continue-on-error: true
|
||||
run: |
|
||||
dotnet-coverage collect \
|
||||
"dotnet test tests/Umbraco.Tests.UnitTests/Umbraco.Tests.UnitTests.csproj --no-build" \
|
||||
--output TestResults/coverage.xml \
|
||||
--output-format xml
|
||||
|
||||
- name: Warn on test failure
|
||||
if: steps.tests.outcome == 'failure'
|
||||
run: |
|
||||
if [ -f TestResults/coverage.xml ]; then
|
||||
echo "::warning::Unit tests failed - SonarCloud analysis will proceed with the collected coverage data"
|
||||
else
|
||||
echo "::warning::Unit tests failed and no coverage data was collected"
|
||||
fi
|
||||
|
||||
- name: End analysis
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: dotnet-sonarscanner end /d:sonar.token="$SONAR_TOKEN"
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"sonar.cs.vscoveragexml.reportsPaths": "TestResults/coverage.xml",
|
||||
"sonar.inclusions": "src/**,templates/**,tools/**,tests/**,.github/**,build/**",
|
||||
"sonar.exclusions": "**/bin/**,**/obj/**,**/node_modules/**,**/lang/*.ts,**/mocks/**,**/wwwroot/**,**/dist-cms/**,**/*.generated.cs,src/Umbraco.Web.UI/umbraco/**,src/Umbraco.Cms.Persistence.EFCore.*/Migrations/**,src/Umbraco.Web.UI.Client/src/packages/core/backend-api/**,**/.nuget/**",
|
||||
"sonar.test.inclusions": "tests/**,**/*.test.ts,**/*.spec.ts",
|
||||
"sonar.typescript.tsconfigPaths": "src/Umbraco.Web.UI.Client/tsconfig.json,src/Umbraco.Web.UI.Client/tsconfig.node.json,src/Umbraco.Web.UI.Login/tsconfig.json"
|
||||
}
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
run:
|
||||
working-directory: src/Umbraco.Web.UI.Client
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -57,7 +57,7 @@ jobs:
|
||||
run:
|
||||
working-directory: src/Umbraco.Web.UI.Client
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v4
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
+2
-9
@@ -52,9 +52,7 @@ tools/docfx/
|
||||
/build/csharp-docs/_site/
|
||||
|
||||
# Local config
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
!.claude/settings.json
|
||||
.claude/settings.local.json
|
||||
.env.local
|
||||
|
||||
# Build
|
||||
@@ -72,8 +70,7 @@ tools/docfx/
|
||||
/src/Umbraco.Cms.StaticAssets/wwwroot/umbraco/assets
|
||||
/src/Umbraco.Cms.StaticAssets/wwwroot/umbraco/js
|
||||
/src/Umbraco.Cms.StaticAssets/wwwroot/umbraco/lib
|
||||
/src/Umbraco.Cms.StaticAssets/wwwroot/umbraco/views/*
|
||||
!/src/Umbraco.Cms.StaticAssets/wwwroot/umbraco/views/errors
|
||||
/src/Umbraco.Cms.StaticAssets/wwwroot/umbraco/views
|
||||
/src/Umbraco.Cms.StaticAssets/wwwroot/umbraco/login
|
||||
|
||||
# Environment specific data
|
||||
@@ -120,7 +117,3 @@ trace.zip
|
||||
/tests/Umbraco.Tests.Integration/appsettings-schema.*.json
|
||||
/tests/Umbraco.Tests.Integration/umbraco-package-schema.json
|
||||
/src/Umbraco.Cms/appsettings-schema.json
|
||||
.playwright-mcp/
|
||||
|
||||
# SonarQube local analysis cache
|
||||
.sonarqube/
|
||||
|
||||
@@ -48,6 +48,7 @@ dotnet_analyzer_diagnostic.category-StyleCop.CSharp.OrderingRules.severity = sug
|
||||
dotnet_analyzer_diagnostic.category-StyleCop.CSharp.MaintainabilityRules.severity = suggestion
|
||||
dotnet_analyzer_diagnostic.category-StyleCop.CSharp.LayoutRules.severity = suggestion
|
||||
|
||||
dotnet_diagnostic.SA1636.severity = none # SA1636: File header copyright text should match
|
||||
dotnet_diagnostic.SA1101.severity = none # PrefixLocalCallsWithThis - stylecop appears to be ignoring dotnet_style_qualification_for_*
|
||||
dotnet_diagnostic.SA1309.severity = none # FieldNamesMustNotBeginWithUnderscore
|
||||
|
||||
|
||||
@@ -46,8 +46,7 @@ Enterprise-grade CMS built on .NET 10.0. This repository contains 21 production
|
||||
- **ASP.NET Core** - Web framework
|
||||
- **Entity Framework Core** - Modern ORM
|
||||
- **OpenIddict** - OAuth 2.0/OpenID Connect authentication
|
||||
- **Microsoft.AspNetCore.OpenApi** - OpenAPI document generation
|
||||
- **Swashbuckle.AspNetCore.SwaggerUI** - Swagger UI for API documentation
|
||||
- **Swashbuckle** - OpenAPI/Swagger documentation
|
||||
- **Lucene.NET** - Full-text search via Examine
|
||||
- **ImageSharp** - Image processing
|
||||
|
||||
@@ -228,11 +227,9 @@ Project ownership is distributed across teams. Check individual project director
|
||||
|
||||
1. **Layered Architecture with Dependency Inversion**
|
||||
- Core defines contracts (interfaces)
|
||||
- Infrastructure implements contracts that need Infrastructure-owned machinery
|
||||
- Infrastructure implements contracts
|
||||
- Web/APIs consume implementations via DI
|
||||
|
||||
**Where service implementations live**: Services whose dependencies are satisfiable from Core interfaces alone (repositories, scope, config, other Core services) live in `Umbraco.Core/Services/` — this covers the majority of domain services (`MemberService`, `ContentService`, `MediaService`, `ContentTypeService`, `EntityService`, `AuditService`, `ExternalMemberService`, etc.). Service implementations only live in `Umbraco.Infrastructure/Services/Implement/` when they genuinely need Infrastructure concerns — Examine indexes (`ContentSearchService`, `MediaSearchService`, `IndexedEntitySearchService`), log files (`LogViewerRepository`), packaging internals (`PackagingService`), webhook firing (`WebhookFiringService`), distributed-job coordination (`DistributedJobService`). When adding a new service, default to Core and only move to Infrastructure if a concrete dependency forces it.
|
||||
|
||||
2. **Interface-First Design**
|
||||
- All services defined as interfaces in Core
|
||||
- Enables testing, polymorphism, extensibility
|
||||
@@ -367,27 +364,16 @@ public interface IMyService
|
||||
|
||||
### Centralized Package Management
|
||||
|
||||
**NuGet package versions** are centralized in `Directory.Packages.props`. There are two `Directory.Packages.props` files in the source tree, with multi-level merging enabled so the test file inherits from the root:
|
||||
|
||||
| File | Scope |
|
||||
|------|-------|
|
||||
| `Directory.Packages.props` (root) | Production source code packages — referenced by all `src/**` projects |
|
||||
| `tests/Directory.Packages.props` | Test-only packages (NUnit, Moq, Bogus, BenchmarkDotNet, etc.) — adds entries on top of the inherited root file |
|
||||
|
||||
When updating dependencies, decide which file the package belongs in:
|
||||
- A package used only by test projects → `tests/Directory.Packages.props`
|
||||
- A package used by any production project (or by both production and tests) → root `Directory.Packages.props`
|
||||
**All NuGet package versions** are centralized in `Directory.Packages.props`. Individual projects do NOT specify versions.
|
||||
|
||||
```xml
|
||||
<!-- Individual projects reference WITHOUT version -->
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" />
|
||||
|
||||
<!-- Versions defined in Directory.Packages.props -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
```
|
||||
|
||||
**Opt-out**: `src/Umbraco.Web.UI/Umbraco.Web.UI.csproj` sets `<ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally>` and specifies versions inline (for `Microsoft.EntityFrameworkCore.Design`, `Microsoft.Build.Tasks.Core`, `Microsoft.ICU.ICU4C.Runtime`, etc.). Update those versions directly in that csproj when bumping. Two further `Directory.Packages.props` files exist under `templates/` for the project/extension templates and have their own version sets — keep `Microsoft.AspNetCore.OpenApi` aligned between the root file and `templates/UmbracoExtension/`.
|
||||
|
||||
### Build Configuration
|
||||
|
||||
- `Directory.Build.props` - Shared properties (target framework, company, copyright)
|
||||
@@ -431,8 +417,7 @@ All APIs use **OpenIddict** (OAuth 2.0/OpenID Connect):
|
||||
APIs use `Asp.Versioning.Mvc`:
|
||||
- Management API: `/umbraco/management/api/v{version}/*`
|
||||
- Delivery API: `/umbraco/delivery/api/v{version}/*`
|
||||
- OpenAPI docs: `/umbraco/openapi/management.json`, `/umbraco/openapi/delivery.json`
|
||||
- Swagger UI: `/umbraco/openapi/`
|
||||
- OpenAPI/Swagger docs per version
|
||||
|
||||
### Updating `OpenApi.json` (Management API)
|
||||
|
||||
@@ -448,14 +433,6 @@ When a PR changes Management API controllers or models, the `OpenApi.json` file
|
||||
|
||||
The backoffice is published to npm as `@umbraco-cms/backoffice`. Runtime dependencies are provided via importmap; npm peerDependencies provide types only. For full details on dependency hoisting, version range logic, and plugin development, see `/src/Umbraco.Web.UI.Client/CLAUDE.md` → "npm Package Publishing".
|
||||
|
||||
### SQL Server 2100-parameter limit
|
||||
|
||||
Any `WHERE IN (@0, @1, ...)` built from a runtime-sized collection risks hitting SQL Server's 2100-parameter ceiling and throwing `SqlException` 8003 in production.
|
||||
|
||||
Batch with `IEnumerable<T>.InGroupsOf(Constants.Sql.MaxParameterCount)` or `Database.FetchByGroups(...)` whenever the collection size is driven by user data — not just when it currently fits. Watch for products of two scaling dimensions (documents × languages, properties × versions) and config-tunable batch sizes whose defaults are safe but ceilings aren't.
|
||||
|
||||
Full guidance, safe patterns and decision rule: see `/src/Umbraco.Infrastructure/CLAUDE.md` → "Avoiding the SQL Server 2100-parameter limit".
|
||||
|
||||
### Known Limitations
|
||||
|
||||
1. **Circular Dependencies**: Avoided via `Lazy<T>` or event notifications
|
||||
@@ -526,42 +503,6 @@ Labels are only added, never removed. Claude applies only labels it is confident
|
||||
|
||||
---
|
||||
|
||||
## 8. Code Comment Policy
|
||||
|
||||
**Default to no comment.** Applies to all code in this repository — C#, TypeScript, Razor, build scripts. Well-named identifiers and small functions are the primary form of self-documentation; comments are a fallback for the rare cases where the code itself cannot carry the meaning.
|
||||
|
||||
### When NOT to comment
|
||||
|
||||
- **Don't restate what the code does.** A line calling `resetState()` does not need `// Reset state`. A method named `validateInput` does not need `// Validate input`.
|
||||
- **Don't narrate a sequence of calls.** If three lines run in order, the order is in the code — don't paraphrase it above.
|
||||
- **Don't reference the current task, fix, callers, or PR.** No `// Fix for X`, `// Used by Y`, `// Added for the Z flow`, `// See PR #1234`. That belongs in commit messages and PR descriptions; in source it rots as the codebase evolves.
|
||||
|
||||
### When a comment IS justified
|
||||
|
||||
Write a comment only when **removing it would leave a future reader confused**. Concretely:
|
||||
|
||||
- **A non-obvious WHY.** A hidden constraint, business rule, or ordering requirement that is not visible from the code.
|
||||
- **A workaround for a specific bug or platform quirk.** Link the issue (`(#21996)`, `https://...`) so the comment can be deleted once the upstream fix lands.
|
||||
- **A subtle invariant** that the type system or method names do not enforce.
|
||||
- **An edge case the code intentionally handles** that would surprise a reader (e.g. "must run before X because Y").
|
||||
- **API documentation** — XML doc comments on C# members, JSDoc on exported TypeScript symbols. Required for the public contract; still keep them concise.
|
||||
|
||||
### TODOs
|
||||
|
||||
Allowed, but cheap to write and cheaper to leave behind. Keep them short and trackable: `// TODO (V19): remove once obsolete overload is gone` or `// TODO: pagination [NL]`. A TODO should have an author or a version trigger.
|
||||
|
||||
---
|
||||
|
||||
## 9. Testing Practices
|
||||
|
||||
### Tests for a bug fix must fail before the fix
|
||||
|
||||
Verify any test you add for a bug fix actually catches the bug: either write the failing test first (TDD), or temporarily revert the production change and confirm the test fails before re-applying. A test that passes both ways proves nothing. Watch for coincidental passes — default seed/sort orders can make a buggy path produce the right answer for the test's specific inputs; construct inputs so the broken and fixed behaviours give visibly different results.
|
||||
|
||||
For integration tests that exercise caching or cache refreshers, see `tests/Umbraco.Tests.Integration/CLAUDE.md` — the harness disables caching by default, which can produce false greens.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Essential Commands
|
||||
@@ -620,8 +561,6 @@ For detailed information about individual projects, see their CLAUDE.md files:
|
||||
- **API Infrastructure**: `/src/Umbraco.Cms.Api.Common/CLAUDE.md` - OpenAPI, authentication, serialization
|
||||
- **Backoffice Frontend**: `/src/Umbraco.Web.UI.Client/CLAUDE.md` - Lit web components, extension system, auth client
|
||||
|
||||
**Important**: When working on backoffice client code (anything under `src/Umbraco.Web.UI.Client/`), read `/src/Umbraco.Web.UI.Client/CLAUDE.md` first. It contains action-specific checklists (deprecation, testing, security, etc.) that are not duplicated here.
|
||||
|
||||
### Getting Help
|
||||
|
||||
- **Official Docs**: https://docs.umbraco.com/
|
||||
|
||||
+1
-11
@@ -41,7 +41,7 @@
|
||||
<PropertyGroup>
|
||||
<GenerateCompatibilitySuppressionFile>false</GenerateCompatibilitySuppressionFile>
|
||||
<EnablePackageValidation>true</EnablePackageValidation>
|
||||
<PackageValidationBaselineVersion>18.0.0</PackageValidationBaselineVersion>
|
||||
<PackageValidationBaselineVersion>17.0.0</PackageValidationBaselineVersion>
|
||||
<EnableStrictModeForCompatibleFrameworksInPackage>true</EnableStrictModeForCompatibleFrameworksInPackage>
|
||||
<EnableStrictModeForCompatibleTfms>true</EnableStrictModeForCompatibleTfms>
|
||||
</PropertyGroup>
|
||||
@@ -64,14 +64,4 @@
|
||||
</_ProjectReferencesWithVersions>
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
<!-- Workaround for https://github.com/umbraco/Umbraco-CMS/issues/23018
|
||||
Due to the amount of XML documentation in this solution, the OpenAPI XML documentation source generator produces
|
||||
too many lines of code causing a StackOverflowException when running on IIS. For that reason we disable the analyzer.
|
||||
See https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/openapi-comments?view=aspnetcore-10.0#disabling-xml-documentation-support -->
|
||||
<Target Name="DisableCompileTimeOpenApiXmlGenerator" BeforeTargets="CoreCompile" Condition="'$(IsPackable)' != 'false' or '$(IsTestProject)' == 'true'">
|
||||
<ItemGroup>
|
||||
<Analyzer Remove="@(Analyzer)" Condition="'%(Filename)' == 'Microsoft.AspNetCore.OpenApi.SourceGenerators'" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
</Project>
|
||||
|
||||
+40
-46
@@ -8,79 +8,76 @@
|
||||
<ItemGroup>
|
||||
<GlobalPackageReference Include="Nerdbank.GitVersioning" Version="3.9.50" />
|
||||
<GlobalPackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
|
||||
<!-- TODO (V18): Bump Umbraco.Code to 3.0.0 stable before release of 18.0.0 -->
|
||||
<GlobalPackageReference Include="Umbraco.Code" Version="3.0.0-beta" />
|
||||
<GlobalPackageReference Include="Umbraco.Code" Version="2.4.0" />
|
||||
<GlobalPackageReference Include="Umbraco.GitVersioning.Extensions" Version="0.2.0" />
|
||||
</ItemGroup>
|
||||
<!-- Microsoft packages -->
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="10.0.7" />
|
||||
<!-- When updating this version, also update templates/UmbracoExtension/Umbraco.Extension.csproj -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" />
|
||||
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="5.3.0" />
|
||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.FileProviders.Embedded" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.FileProviders.Physical" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Identity.Core" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Identity.Stores" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Hybrid" Version="10.5.0" />
|
||||
<PackageVersion Include="System.Linq.Async" Version="7.0.1" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" />
|
||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.FileProviders.Embedded" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.FileProviders.Physical" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Identity.Core" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Identity.Stores" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Caching.Hybrid" Version="10.4.0" />
|
||||
<PackageVersion Include="System.Linq.Async" Version="7.0.0" />
|
||||
</ItemGroup>
|
||||
<!-- Umbraco packages -->
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Umbraco.JsonSchema.Extensions" Version="0.4.0" />
|
||||
<PackageVersion Include="Umbraco.JsonSchema.Extensions" Version="0.3.0" />
|
||||
</ItemGroup>
|
||||
<!-- Third-party packages -->
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Asp.Versioning.Mvc" Version="10.0.0" />
|
||||
<PackageVersion Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" />
|
||||
<PackageVersion Include="Asp.Versioning.Mvc" Version="8.1.1" />
|
||||
<PackageVersion Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.1" />
|
||||
<PackageVersion Include="Dazinator.Extensions.FileProviders" Version="2.0.0" />
|
||||
<PackageVersion Include="Examine" Version="3.8.0" />
|
||||
<PackageVersion Include="Examine.Core" Version="3.8.0" />
|
||||
<PackageVersion Include="Examine" Version="3.7.1" />
|
||||
<PackageVersion Include="Examine.Core" Version="3.7.1" />
|
||||
<PackageVersion Include="HtmlAgilityPack" Version="1.12.4" />
|
||||
<PackageVersion Include="JsonPatch.Net" Version="3.3.0" />
|
||||
<PackageVersion Include="K4os.Compression.LZ4" Version="1.3.8" />
|
||||
<PackageVersion Include="MailKit" Version="4.16.0" />
|
||||
<PackageVersion Include="Markdig" Version="1.1.3" />
|
||||
<PackageVersion Include="MailKit" Version="4.15.1" />
|
||||
<PackageVersion Include="Markdig" Version="0.45.0" />
|
||||
<PackageVersion Include="Markdown" Version="2.2.1" />
|
||||
<PackageVersion Include="MessagePack" Version="3.1.7" />
|
||||
<PackageVersion Include="MessagePack" Version="3.1.4" />
|
||||
<PackageVersion Include="MiniProfiler.AspNetCore.Mvc" Version="4.5.4" />
|
||||
<PackageVersion Include="MiniProfiler.Shared" Version="4.5.4" />
|
||||
<PackageVersion Include="ncrontab" Version="3.4.0" />
|
||||
<PackageVersion Include="NPoco" Version="6.2.0" />
|
||||
<PackageVersion Include="NPoco.SqlServer" Version="6.2.0" />
|
||||
<PackageVersion Include="OpenIddict.Abstractions" Version="7.5.0" />
|
||||
<PackageVersion Include="OpenIddict.AspNetCore" Version="7.5.0" />
|
||||
<PackageVersion Include="OpenIddict.EntityFrameworkCore" Version="7.5.0" />
|
||||
<PackageVersion Include="OpenIddict.Abstractions" Version="7.2.0" />
|
||||
<PackageVersion Include="OpenIddict.AspNetCore" Version="7.2.0" />
|
||||
<PackageVersion Include="OpenIddict.EntityFrameworkCore" Version="7.2.0" />
|
||||
<PackageVersion Include="Serilog" Version="4.3.1" />
|
||||
<PackageVersion Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageVersion Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
<PackageVersion Include="Serilog.Enrichers.Process" Version="3.0.0" />
|
||||
<PackageVersion Include="Serilog.Enrichers.Thread" Version="4.0.0" />
|
||||
<PackageVersion Include="Serilog.Expressions" Version="5.0.0" />
|
||||
<PackageVersion Include="Serilog.Extensions.Hosting" Version="10.0.0" />
|
||||
<PackageVersion Include="Serilog.Extensions.Hosting" Version="9.0.0" />
|
||||
<PackageVersion Include="Serilog.Formatting.Compact" Version="3.0.0" />
|
||||
<PackageVersion Include="Serilog.Formatting.Compact.Reader" Version="4.0.0" />
|
||||
<PackageVersion Include="Serilog.Settings.Configuration" Version="10.0.0" />
|
||||
<PackageVersion Include="Serilog.Settings.Configuration" Version="9.0.0" />
|
||||
<PackageVersion Include="Serilog.Sinks.Async" Version="2.1.0" />
|
||||
<PackageVersion Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
<PackageVersion Include="Serilog.Sinks.Map" Version="2.0.0" />
|
||||
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" />
|
||||
<PackageVersion Include="SixLabors.ImageSharp.Web" Version="3.2.0" />
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.1.7" />
|
||||
<!-- When updating this version, also update templates/UmbracoExtension/Umbraco.Extension.csproj -->
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.1.4" />
|
||||
</ItemGroup>
|
||||
<!-- Transitive pinned versions (only required because our direct dependencies have vulnerable versions of transitive dependencies) -->
|
||||
<ItemGroup>
|
||||
@@ -91,8 +88,5 @@
|
||||
<!-- Markdown references vulnerable version of the following: -->
|
||||
<!-- TODO (V19): Remove these pinned dependencies when the Markdown dependency is removed. -->
|
||||
<PackageVersion Include="System.Text.RegularExpressions" Version="4.3.1" />
|
||||
<!-- Examine (via Microsoft.AspNetCore.DataProtection 8.0.4) references a vulnerable version of the following: -->
|
||||
<!-- TODO: Remove this pinned dependency when Examine updates its Microsoft.AspNetCore.DataProtection reference. -->
|
||||
<PackageVersion Include="System.Security.Cryptography.Xml" Version="10.0.7" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
+123
-71
@@ -45,7 +45,7 @@ parameters:
|
||||
- name: integrationNonReleaseTestFilter
|
||||
displayName: TestFilter used for non-release type builds
|
||||
type: string
|
||||
default: "TestCategory!=LongRunning&TestCategory!=NonCritical"
|
||||
default: "--filter TestCategory!=LongRunning&TestCategory!=NonCritical"
|
||||
- name: integrationReleaseTestFilter
|
||||
displayName: TestFilter used for release type builds
|
||||
type: string
|
||||
@@ -53,7 +53,7 @@ parameters:
|
||||
- name: nonWindowsIntegrationNonReleaseTestFilter
|
||||
displayName: TestFilter used for non-release type builds on non Windows agents
|
||||
type: string
|
||||
default: "TestCategory!=LongRunning&TestCategory!=NonCritical"
|
||||
default: "--filter TestCategory!=LongRunning&TestCategory!=NonCritical"
|
||||
- name: nonWindowsIntegrationReleaseTestFilter
|
||||
displayName: TestFilter used for release type builds on non Windows agents
|
||||
type: string
|
||||
@@ -188,9 +188,16 @@ stages:
|
||||
parameters:
|
||||
nodeVersion: ${{ variables.nodeVersion }}
|
||||
npm_config_cache: ${{ variables.npm_config_cache }}
|
||||
- template: templates/set-npm-version.yml
|
||||
parameters:
|
||||
workingDirectory: tests/Umbraco.Tests.AcceptanceTest
|
||||
- bash: |
|
||||
echo "##[command]Install nbgv"
|
||||
dotnet tool install --tool-path . nbgv
|
||||
echo "##[command]Running nbgv get-version"
|
||||
PACKAGE_VERSION=$(nbgv get-version -v NpmPackageVersion)
|
||||
echo "##[command]Running npm version"
|
||||
echo "##[debug]Version: $PACKAGE_VERSION"
|
||||
cd tests/Umbraco.Tests.AcceptanceTest
|
||||
npm version $PACKAGE_VERSION --allow-same-version --no-git-tag-version
|
||||
displayName: Set NPM Version
|
||||
- bash: |
|
||||
echo "##[command]Running npm pack"
|
||||
mkdir $(Build.ArtifactStagingDirectory)/npm-testhelpers
|
||||
@@ -455,13 +462,13 @@ stages:
|
||||
projects: "tests/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj"
|
||||
testRunTitle: Integration Tests SQLite - $(Agent.OS)
|
||||
${{ if and(eq(variables['Agent.OS'],'Windows_NT'), or(variables.releaseTestFilter, parameters.forceReleaseTestFilter)) }}:
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.integrationReleaseTestFilter}}'
|
||||
${{ elseif eq(variables['Agent.OS'],'Windows_NT') }}:
|
||||
arguments: '--filter "$(testFilter) & ${{parameters.integrationNonReleaseTestFilter}}" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.integrationNonReleaseTestFilter}}'
|
||||
${{ elseif or(variables.releaseTestFilter, parameters.forceReleaseTestFilter) }}:
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.nonWindowsIntegrationReleaseTestFilter}}'
|
||||
${{ else }}:
|
||||
arguments: '--filter "$(testFilter) & ${{parameters.nonWindowsIntegrationNonReleaseTestFilter}}" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.nonWindowsIntegrationNonReleaseTestFilter}}'
|
||||
# Integration Tests (SQL Server)
|
||||
- job:
|
||||
timeoutInMinutes: 180
|
||||
@@ -569,13 +576,13 @@ stages:
|
||||
projects: "tests/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj"
|
||||
testRunTitle: Integration Tests SQL Server - $(Agent.OS)
|
||||
${{ if and(eq(variables['Agent.OS'],'Windows_NT'), or(variables.releaseTestFilter, parameters.forceReleaseTestFilter)) }}:
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.integrationReleaseTestFilter}}'
|
||||
${{ elseif eq(variables['Agent.OS'],'Windows_NT') }}:
|
||||
arguments: '--filter "$(testFilter) & ${{parameters.integrationNonReleaseTestFilter}}" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.integrationNonReleaseTestFilter}}'
|
||||
${{ elseif or(variables.releaseTestFilter, parameters.forceReleaseTestFilter) }}:
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.nonWindowsIntegrationReleaseTestFilter}}'
|
||||
${{ else }}:
|
||||
arguments: '--filter "$(testFilter) & ${{parameters.nonWindowsIntegrationNonReleaseTestFilter}}" --configuration $(buildConfiguration) --no-build'
|
||||
arguments: '--filter "$(testFilter)" --configuration $(buildConfiguration) --no-build ${{parameters.nonWindowsIntegrationNonReleaseTestFilter}}'
|
||||
|
||||
# Stop SQL Server
|
||||
- pwsh: docker stop mssql
|
||||
@@ -825,56 +832,84 @@ stages:
|
||||
publishFeedCredentials: "MyGet - Umbraco Nightly"
|
||||
${{ else }}:
|
||||
publishFeedCredentials: "MyGet - Pre-releases"
|
||||
# Pre-release/nightly feeds: keep the `latest` dist-tag default (no `next` split).
|
||||
- job:
|
||||
displayName: Push to pre-release feed (npm)
|
||||
steps:
|
||||
- template: templates/npm-publish.yml
|
||||
parameters:
|
||||
artifactName: npm
|
||||
- checkout: none
|
||||
- download: current
|
||||
artifact: npm
|
||||
- bash: |
|
||||
# Check if we are on a nightly build
|
||||
if [ $isNightly = "False" ]; then
|
||||
echo "##[debug]Prerelease build detected"
|
||||
registry="https://www.myget.org/F/umbracoprereleases/npm/"
|
||||
else
|
||||
echo "##[debug]Nightly build detected"
|
||||
registry="https://www.myget.org/F/umbraconightly/npm/"
|
||||
fi
|
||||
echo "@umbraco-cms:registry=$registry" >> .npmrc
|
||||
env:
|
||||
isNightly: ${{parameters.isNightly}}
|
||||
workingDirectory: $(Pipeline.Workspace)/npm
|
||||
displayName: Add scoped registry to .npmrc
|
||||
- task: npmAuthenticate@0
|
||||
displayName: Authenticate with npm (MyGet)
|
||||
inputs:
|
||||
workingFile: "$(Pipeline.Workspace)/npm/.npmrc"
|
||||
customEndpoint: "MyGet (npm) - Umbracoprereleases, MyGet (npm) - Umbraconightly"
|
||||
displayName: Push to npm (MyGet)
|
||||
${{ if eq(parameters.isNightly, true) }}:
|
||||
registry: https://www.myget.org/F/umbraconightly/npm/
|
||||
${{ else }}:
|
||||
registry: https://www.myget.org/F/umbracoprereleases/npm/
|
||||
- bash: |
|
||||
# Setup temp npm project to load in defaults from the local .npmrc
|
||||
npm init -y
|
||||
|
||||
# Find the first .tgz file in the current directory and publish it
|
||||
files=( ./*.tgz )
|
||||
npm publish "${files[0]}"
|
||||
displayName: Push to npm (MyGet)
|
||||
workingDirectory: $(Pipeline.Workspace)/npm
|
||||
- job: PublishTestHelpersNpm
|
||||
displayName: Push TestHelpers to pre-release feed (npm)
|
||||
steps:
|
||||
- template: templates/npm-publish.yml
|
||||
parameters:
|
||||
artifactName: npm-testhelpers
|
||||
- checkout: none
|
||||
- download: current
|
||||
artifact: npm-testhelpers
|
||||
- bash: |
|
||||
# Check if we are on a nightly build
|
||||
if [ $isNightly = "False" ]; then
|
||||
echo "##[debug]Prerelease build detected"
|
||||
registry="https://www.myget.org/F/umbracoprereleases/npm/"
|
||||
else
|
||||
echo "##[debug]Nightly build detected"
|
||||
registry="https://www.myget.org/F/umbraconightly/npm/"
|
||||
fi
|
||||
echo "@umbraco-cms:registry=$registry" >> .npmrc
|
||||
env:
|
||||
isNightly: ${{parameters.isNightly}}
|
||||
workingDirectory: $(Pipeline.Workspace)/npm-testhelpers
|
||||
displayName: Add scoped registry to .npmrc
|
||||
- task: npmAuthenticate@0
|
||||
displayName: Authenticate with npm (MyGet)
|
||||
inputs:
|
||||
workingFile: "$(Pipeline.Workspace)/npm-testhelpers/.npmrc"
|
||||
customEndpoint: "MyGet (npm) - Umbracoprereleases, MyGet (npm) - Umbraconightly"
|
||||
displayName: Push test helpers to npm (MyGet)
|
||||
${{ if eq(parameters.isNightly, true) }}:
|
||||
registry: https://www.myget.org/F/umbraconightly/npm/
|
||||
${{ else }}:
|
||||
registry: https://www.myget.org/F/umbracoprereleases/npm/
|
||||
- bash: |
|
||||
# Setup temp npm project to load in defaults from the local .npmrc
|
||||
npm init -y
|
||||
|
||||
# Find the first .tgz file in the current directory and publish it
|
||||
files=( ./*.tgz )
|
||||
npm publish "${files[0]}"
|
||||
displayName: Push test helpers to npm (MyGet)
|
||||
workingDirectory: $(Pipeline.Workspace)/npm-testhelpers
|
||||
|
||||
- stage: Deploy_NuGet
|
||||
displayName: NuGet release
|
||||
dependsOn: Deploy_MyGet
|
||||
# Run only when Deploy_MyGet actually ran (succeeded or failed) — not when it was skipped due to an upstream test failure.
|
||||
# Inspect Deploy_MyGet's direct result rather than succeeded()/failed(), which are transitive across the full ancestor graph.
|
||||
# Approval is required every run via the WaitForApproval job below.
|
||||
condition: and(in(dependencies.Deploy_MyGet.result, 'Succeeded', 'SucceededWithIssues', 'Failed'), or(eq(dependencies.Build.outputs['A.build.NBGV_PublicRelease'], 'True'), ${{parameters.nuGetDeploy}}))
|
||||
condition: and(succeeded(), or(eq(dependencies.Build.outputs['A.build.NBGV_PublicRelease'], 'True'), ${{parameters.nuGetDeploy}}))
|
||||
jobs:
|
||||
- job: WaitForApproval
|
||||
displayName: Wait for manual approval
|
||||
pool: server
|
||||
steps:
|
||||
- task: ManualValidation@0
|
||||
displayName: Manual approval to push to NuGet
|
||||
timeoutInMinutes: 4320 # 3 days
|
||||
inputs:
|
||||
notifyUsers: ''
|
||||
instructions: 'Approve to push the NuGet release.'
|
||||
onTimeout: 'reject'
|
||||
- job: Push
|
||||
displayName: Push to NuGet
|
||||
dependsOn: WaitForApproval
|
||||
- job:
|
||||
pool:
|
||||
vmImage: "windows-latest" # NuGetCommand@2 is no longer supported on Ubuntu 24.04 so we'll use windows until an alternative is available.
|
||||
displayName: Push to NuGet
|
||||
steps:
|
||||
- checkout: none
|
||||
- task: DownloadPipelineArtifact@2
|
||||
@@ -892,36 +927,56 @@ stages:
|
||||
|
||||
- stage: Deploy_Npm
|
||||
displayName: Npm release
|
||||
# Inspect Deploy_NuGet.result directly so a MyGet failure (which is in the transitive ancestor graph)
|
||||
# doesn't cascade-skip this stage via succeeded(). Deploy_NuGet must itself have succeeded — a NuGet
|
||||
# failure deliberately blocks the npm release.
|
||||
condition: and(in(dependencies.Deploy_NuGet.result, 'Succeeded', 'SucceededWithIssues'), or(eq(dependencies.Build.outputs['A.build.NBGV_PublicRelease'], 'True'), ${{parameters.npmDeploy}}))
|
||||
condition: and(succeeded(), or(eq(dependencies.Build.outputs['A.build.NBGV_PublicRelease'], 'True'), ${{parameters.npmDeploy}}))
|
||||
dependsOn:
|
||||
- Deploy_NuGet
|
||||
variables:
|
||||
# `latest` for stable releases, `next` for prereleases.
|
||||
npmDistTag: $[ iif(eq(stageDependencies.Build.A.outputs['build.NBGV_PrereleaseVersionNoLeadingHyphen'], ''), 'latest', 'next') ]
|
||||
jobs:
|
||||
- job: Publish
|
||||
displayName: Push to NPM
|
||||
steps:
|
||||
- template: templates/npm-publish.yml
|
||||
parameters:
|
||||
artifactName: npm
|
||||
registry: https://registry.npmjs.org/
|
||||
- checkout: none
|
||||
- download: current
|
||||
artifact: npm
|
||||
- bash: echo "@umbraco-cms:registry=https://registry.npmjs.org" >> .npmrc
|
||||
workingDirectory: $(Pipeline.Workspace)/npm
|
||||
displayName: Add scoped registry to .npmrc
|
||||
- task: npmAuthenticate@0
|
||||
displayName: Authenticate with npm
|
||||
inputs:
|
||||
workingFile: $(Pipeline.Workspace)/npm/.npmrc
|
||||
customEndpoint: "NPM - Umbraco Backoffice"
|
||||
displayName: Push to npm
|
||||
npmTag: $(npmDistTag)
|
||||
- script: |
|
||||
# Setup temp npm project to load in defaults from the local .npmrc
|
||||
npm init -y
|
||||
|
||||
# Find the first .tgz file in the current directory and publish it
|
||||
files=( ./*.tgz )
|
||||
npm publish "${files[0]}"
|
||||
displayName: Push to npm
|
||||
workingDirectory: $(Pipeline.Workspace)/npm
|
||||
- job: PublishTestHelpers
|
||||
displayName: Push Test Helpers to NPM
|
||||
steps:
|
||||
- template: templates/npm-publish.yml
|
||||
parameters:
|
||||
artifactName: npm-testhelpers
|
||||
registry: https://registry.npmjs.org/
|
||||
- checkout: none
|
||||
- download: current
|
||||
artifact: npm-testhelpers
|
||||
- bash: echo "@umbraco-cms:registry=https://registry.npmjs.org" >> .npmrc
|
||||
workingDirectory: $(Pipeline.Workspace)/npm-testhelpers
|
||||
displayName: Add scoped registry to .npmrc
|
||||
- task: npmAuthenticate@0
|
||||
displayName: Authenticate with npm
|
||||
inputs:
|
||||
workingFile: $(Pipeline.Workspace)/npm-testhelpers/.npmrc
|
||||
customEndpoint: "NPM - Umbraco Backoffice"
|
||||
displayName: Push test helpers to npm
|
||||
npmTag: $(npmDistTag)
|
||||
- script: |
|
||||
# Setup temp npm project to load in defaults from the local .npmrc
|
||||
npm init -y
|
||||
|
||||
# Find the first .tgz file in the current directory and publish it
|
||||
files=( ./*.tgz )
|
||||
npm publish "${files[0]}"
|
||||
displayName: Push test helpers to npm
|
||||
workingDirectory: $(Pipeline.Workspace)/npm-testhelpers
|
||||
|
||||
- stage: Upload_API_Docs
|
||||
pool:
|
||||
@@ -933,10 +988,7 @@ stages:
|
||||
- Build
|
||||
- Build_Docs
|
||||
- Deploy_NuGet
|
||||
# Build_Docs must have produced artifacts (we won't upload anything otherwise) and Deploy_NuGet must
|
||||
# have succeeded — a NuGet failure deliberately blocks the docs upload. Direct result checks avoid
|
||||
# transitive succeeded()/failed() which would cascade-skip on a MyGet failure.
|
||||
condition: and(in(dependencies.Build_Docs.result, 'Succeeded', 'SucceededWithIssues'), in(dependencies.Deploy_NuGet.result, 'Succeeded', 'SucceededWithIssues'), or(eq(dependencies.Build.outputs['A.build.NBGV_PublicRelease'], 'True'), ${{parameters.uploadApiDocs}}))
|
||||
condition: and(succeeded(), or(eq(dependencies.Build.outputs['A.build.NBGV_PublicRelease'], 'True'), ${{parameters.uploadApiDocs}}))
|
||||
jobs:
|
||||
- job:
|
||||
displayName: Upload C# Docs
|
||||
|
||||
@@ -4,8 +4,8 @@ pr: none
|
||||
trigger: none
|
||||
|
||||
schedules:
|
||||
- cron: '0 0 * * *'
|
||||
displayName: Daily 0AM build (main)
|
||||
- cron: '0 3 * * *'
|
||||
displayName: Daily 3AM build (main)
|
||||
branches:
|
||||
include:
|
||||
- main
|
||||
@@ -117,7 +117,7 @@ stages:
|
||||
- stage: Integration
|
||||
displayName: Integration Tests
|
||||
dependsOn: Build
|
||||
condition: and(succeeded(), ${{ eq(parameters.skipIntegrationTests, false) }})
|
||||
condition: ${{ eq(parameters.skipIntegrationTests, false) }}
|
||||
jobs:
|
||||
# Integration Tests (SQLite)
|
||||
- job:
|
||||
@@ -199,37 +199,31 @@ stages:
|
||||
SA_PASSWORD: UmbracoAcceptance123!
|
||||
strategy:
|
||||
matrix:
|
||||
# Windows is split into 5 parts (ManagementApi split in two to avoid memory pressure on LocalDb); Linux into 4.
|
||||
WindowsPart1Of5:
|
||||
# We split the tests into 4 parts for each OS to reduce the time it takes to run them on the pipeline
|
||||
WindowsPart1Of4:
|
||||
vmImage: "windows-latest"
|
||||
Tests__Database__DatabaseType: LocalDb
|
||||
Tests__Database__SQLServerMasterConnectionString: N/A
|
||||
# Filter tests that are part of the Umbraco.Infrastructure namespace but not part of the Umbraco.Infrastructure.Service namespace
|
||||
testFilter: "(FullyQualifiedName~Umbraco.Infrastructure) & (FullyQualifiedName!~Umbraco.Infrastructure.Service)"
|
||||
WindowsPart2Of5:
|
||||
WindowsPart2Of4:
|
||||
vmImage: "windows-latest"
|
||||
Tests__Database__DatabaseType: LocalDb
|
||||
Tests__Database__SQLServerMasterConnectionString: N/A
|
||||
# Filter tests that are part of the Umbraco.Infrastructure.Service namespace
|
||||
testFilter: "(FullyQualifiedName~Umbraco.Infrastructure.Service)"
|
||||
WindowsPart3Of5:
|
||||
WindowsPart3Of4:
|
||||
vmImage: "windows-latest"
|
||||
Tests__Database__DatabaseType: LocalDb
|
||||
Tests__Database__SQLServerMasterConnectionString: N/A
|
||||
# Filter tests that are not part of the Umbraco.Infrastructure and ManagementApi namespace.
|
||||
testFilter: "(FullyQualifiedName!~Umbraco.Infrastructure) & (FullyQualifiedName!~ManagementApi)"
|
||||
WindowsPart4Of5:
|
||||
WindowsPart4Of4:
|
||||
vmImage: "windows-latest"
|
||||
Tests__Database__DatabaseType: LocalDb
|
||||
Tests__Database__SQLServerMasterConnectionString: N/A
|
||||
# ManagementApi, heavier sub-namespaces. Trailing dots prevent "User." from matching "UserGroup." etc.
|
||||
testFilter: "FullyQualifiedName~ManagementApi & (FullyQualifiedName~ManagementApi.Element. | FullyQualifiedName~ManagementApi.User. | FullyQualifiedName~ManagementApi.Document. | FullyQualifiedName~ManagementApi.DataType. | FullyQualifiedName~ManagementApi.DocumentType. | FullyQualifiedName~ManagementApi.MediaType. | FullyQualifiedName~ManagementApi.Template.)"
|
||||
WindowsPart5Of5:
|
||||
vmImage: "windows-latest"
|
||||
Tests__Database__DatabaseType: LocalDb
|
||||
Tests__Database__SQLServerMasterConnectionString: N/A
|
||||
# ManagementApi, remainder (complement of Part4). vstest filters do not support group
|
||||
testFilter: "FullyQualifiedName~ManagementApi & FullyQualifiedName!~ManagementApi.Element. & FullyQualifiedName!~ManagementApi.User. & FullyQualifiedName!~ManagementApi.Document. & FullyQualifiedName!~ManagementApi.DataType. & FullyQualifiedName!~ManagementApi.DocumentType. & FullyQualifiedName!~ManagementApi.MediaType. & FullyQualifiedName!~ManagementApi.Template."
|
||||
# Filter tests that are part of the ManagementApi namespace.
|
||||
testFilter: "(FullyQualifiedName~ManagementApi)"
|
||||
LinuxPart1Of4:
|
||||
vmImage: "ubuntu-latest"
|
||||
Tests__Database__DatabaseType: SqlServer
|
||||
@@ -325,8 +319,8 @@ stages:
|
||||
|
||||
- stage: DefaultConfigE2E
|
||||
displayName: Default Config E2E Tests
|
||||
dependsOn: [Build, Integration]
|
||||
condition: in(dependencies.Build.result, 'Succeeded', 'SucceededWithIssues')
|
||||
dependsOn: Integration
|
||||
condition: always()
|
||||
variables:
|
||||
npm_config_cache: $(Pipeline.Workspace)/.npm_e2e
|
||||
# Enable console logging in Release mode
|
||||
@@ -506,8 +500,8 @@ stages:
|
||||
|
||||
- stage: AdditionalConfigE2E
|
||||
displayName: Additional Config E2E Tests
|
||||
dependsOn: [Build, DefaultConfigE2E]
|
||||
condition: in(dependencies.Build.result, 'Succeeded', 'SucceededWithIssues')
|
||||
dependsOn: DefaultConfigE2E
|
||||
condition: always()
|
||||
variables:
|
||||
npm_config_cache: $(Pipeline.Workspace)/.npm_e2e
|
||||
ASPNETCORE_URLS: https://localhost:44331
|
||||
|
||||
@@ -6,9 +6,16 @@ steps:
|
||||
versionSource: 'fromFile'
|
||||
versionFilePath: src/Umbraco.Web.UI.Client/.nvmrc
|
||||
|
||||
- template: set-npm-version.yml
|
||||
parameters:
|
||||
workingDirectory: src/Umbraco.Web.UI.Client
|
||||
- bash: |
|
||||
echo "##[command]Install nbgv"
|
||||
dotnet tool install --tool-path . nbgv
|
||||
echo "##[command]Running nbgv get-version"
|
||||
PACKAGE_VERSION=$(nbgv get-version -v NpmPackageVersion)
|
||||
echo "##[command]Running npm version"
|
||||
echo "##[debug]Version: $PACKAGE_VERSION"
|
||||
cd src/Umbraco.Web.UI.Client
|
||||
npm version $PACKAGE_VERSION --allow-same-version --no-git-tag-version
|
||||
displayName: Set NPM Version
|
||||
|
||||
- task: Cache@2
|
||||
displayName: Cache node_modules
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
parameters:
|
||||
- name: artifactName # "npm" or "npm-testhelpers"
|
||||
type: string
|
||||
- name: registry # scoped-registry URL to publish to
|
||||
type: string
|
||||
- name: customEndpoint # npmAuthenticate service connection(s)
|
||||
type: string
|
||||
- name: displayName # label for the publish step
|
||||
type: string
|
||||
- name: npmTag # dist-tag to publish under
|
||||
type: string
|
||||
default: latest
|
||||
|
||||
steps:
|
||||
- checkout: none
|
||||
- download: current
|
||||
artifact: ${{ parameters.artifactName }}
|
||||
- script: npm config set @umbraco-cms:registry ${{ parameters.registry }} --location=project
|
||||
displayName: Add scoped registry to .npmrc
|
||||
workingDirectory: $(Pipeline.Workspace)/${{ parameters.artifactName }}
|
||||
- task: npmAuthenticate@0
|
||||
displayName: Authenticate with npm
|
||||
inputs:
|
||||
workingFile: $(Pipeline.Workspace)/${{ parameters.artifactName }}/.npmrc
|
||||
customEndpoint: ${{ parameters.customEndpoint }}
|
||||
- script: npm publish *.tgz --tag ${{ parameters.npmTag }}
|
||||
displayName: ${{ parameters.displayName }}
|
||||
workingDirectory: $(Pipeline.Workspace)/${{ parameters.artifactName }}
|
||||
@@ -1,15 +0,0 @@
|
||||
parameters:
|
||||
- name: workingDirectory
|
||||
type: string
|
||||
|
||||
steps:
|
||||
- bash: |
|
||||
echo "##[command]Install nbgv"
|
||||
dotnet tool install --tool-path . nbgv
|
||||
echo "##[command]Running nbgv get-version"
|
||||
PACKAGE_VERSION=$(nbgv get-version -v NpmPackageVersion)
|
||||
echo "##[command]Running npm version"
|
||||
echo "##[debug]Version: $PACKAGE_VERSION"
|
||||
cd ${{ parameters.workingDirectory }}
|
||||
npm version $PACKAGE_VERSION --allow-same-version --no-git-tag-version
|
||||
displayName: Set NPM Version
|
||||
@@ -13,8 +13,7 @@ Shared infrastructure for Umbraco CMS REST APIs (Management and Delivery).
|
||||
### Key Technologies
|
||||
|
||||
- **ASP.NET Core** - Web framework
|
||||
- **Microsoft.AspNetCore.OpenApi** - OpenAPI document generation
|
||||
- **Swashbuckle.AspNetCore.SwaggerUI** - Swagger UI for browsing API documentation
|
||||
- **Swashbuckle** - OpenAPI/Swagger documentation generation
|
||||
- **OpenIddict** - OAuth 2.0/OpenID Connect authentication
|
||||
- **Asp.Versioning** - API versioning
|
||||
- **System.Text.Json** - Polymorphic JSON serialization
|
||||
@@ -28,18 +27,14 @@ Shared infrastructure for Umbraco CMS REST APIs (Management and Delivery).
|
||||
|
||||
```
|
||||
Umbraco.Cms.Api.Common/
|
||||
├── OpenApi/ # OpenAPI transformers and schema generators
|
||||
│ ├── UmbracoSchemaIdGenerator.cs # Generates schema IDs (e.g., "PagedUserModel")
|
||||
│ ├── UmbracoOperationIdTransformer.cs # Generates operation IDs
|
||||
│ ├── SortTagsAndPathsTransformer.cs # Sorts OpenAPI tags and paths
|
||||
│ ├── TagActionsByGroupNameTransformer.cs # Tags operations by controller group
|
||||
│ ├── FixFileReturnTypesTransformer.cs # Fixes file return type schemas
|
||||
│ ├── RequireNonNullablePropertiesSchemaTransformer.cs # Schema nullability
|
||||
│ └── OpenApiRouteTemplatePipelineFilter.cs # Adds OpenAPI endpoints
|
||||
├── OpenApi/ # Schema/Operation ID handlers for Swagger
|
||||
│ ├── SchemaIdHandler.cs # Generates schema IDs (e.g., "PagedUserModel")
|
||||
│ ├── OperationIdHandler.cs # Generates operation IDs
|
||||
│ └── SubTypesHandler.cs # Polymorphism support
|
||||
├── Serialization/ # JSON type resolution
|
||||
│ └── UmbracoJsonTypeInfoResolver.cs
|
||||
├── Configuration/ # Options configuration
|
||||
│ ├── ConfigureUmbracoOpenApiOptionsBase.cs
|
||||
│ ├── ConfigureUmbracoSwaggerGenOptions.cs
|
||||
│ └── ConfigureOpenIddict.cs
|
||||
├── DependencyInjection/ # Service registration
|
||||
│ ├── UmbracoBuilderApiExtensions.cs
|
||||
@@ -52,8 +47,9 @@ Umbraco.Cms.Api.Common/
|
||||
|
||||
### Design Patterns
|
||||
|
||||
1. **Builder Pattern** - `ProblemDetailsBuilder` for fluent error responses
|
||||
2. **Options Pattern** - All configuration via `IConfigureOptions<T>`
|
||||
1. **Strategy Pattern** - `ISchemaIdHandler`, `IOperationIdHandler` (extensible via inheritance)
|
||||
2. **Builder Pattern** - `ProblemDetailsBuilder` for fluent error responses
|
||||
3. **Options Pattern** - All configuration via `IConfigureOptions<T>`
|
||||
|
||||
---
|
||||
|
||||
@@ -65,12 +61,25 @@ See "Quick Reference" section at bottom for common commands.
|
||||
|
||||
## 3. Key Patterns
|
||||
|
||||
### Schema ID Generation (OpenApi/UmbracoSchemaIdGenerator.cs)
|
||||
### Virtual Handlers for Extensibility
|
||||
|
||||
Static utility class that generates OpenAPI schema IDs following Umbraco's naming conventions:
|
||||
Handlers are intentionally virtual to allow consuming APIs to override:
|
||||
|
||||
```csharp
|
||||
// Add "Model" suffix to avoid TypeScript name clashes
|
||||
// NOTE: Left unsealed on purpose, so it is extendable.
|
||||
public class SchemaIdHandler : ISchemaIdHandler
|
||||
{
|
||||
public virtual bool CanHandle(Type type) { }
|
||||
public virtual string Handle(Type type) { }
|
||||
}
|
||||
```
|
||||
|
||||
**Why**: Management and Delivery APIs can customize schema/operation ID generation.
|
||||
|
||||
### Schema ID Sanitization (OpenApi/SchemaIdHandler.cs:24-29, 32)
|
||||
|
||||
```csharp
|
||||
// Add "Model" suffix to avoid TypeScript name clashes (lines 24-29)
|
||||
if (name.EndsWith("Model") == false)
|
||||
{
|
||||
// because some models names clash with common classes in TypeScript (i.e. Document),
|
||||
@@ -78,12 +87,10 @@ if (name.EndsWith("Model") == false)
|
||||
name = $"{name}Model";
|
||||
}
|
||||
|
||||
// Remove invalid characters to prevent OpenAPI generation errors
|
||||
// Remove invalid characters to prevent OpenAPI generation errors (line 32)
|
||||
return Regex.Replace(name, @"[^\w]", string.Empty);
|
||||
```
|
||||
|
||||
**Generic Type Handling**: `PagedViewModel<RelationItemViewModel>` becomes `PagedRelationItemModel`
|
||||
|
||||
### Polymorphic Deserialization (Serialization/UmbracoJsonTypeInfoResolver.cs:29-35)
|
||||
|
||||
```csharp
|
||||
@@ -109,12 +116,9 @@ if (type.IsInterface is false)
|
||||
dotnet test tests/Umbraco.Tests.Integration/
|
||||
|
||||
# Verify OpenAPI generation
|
||||
# 1. Run the application: dotnet run --project src/Umbraco.Web.UI
|
||||
# 2. Navigate to /umbraco/openapi/ for Swagger UI
|
||||
# 1. Run Management API
|
||||
# 2. Navigate to /umbraco/swagger/
|
||||
# 3. Check schema IDs and operation IDs
|
||||
# OpenAPI JSON documents available at:
|
||||
# - /umbraco/openapi/management.json (Management API)
|
||||
# - /umbraco/openapi/delivery.json (Delivery API)
|
||||
```
|
||||
|
||||
**Focus areas when testing**:
|
||||
@@ -203,24 +207,49 @@ catch (NotSupportedException exception)
|
||||
|
||||
**Issue**: Type names like `Document` clash with TypeScript built-ins.
|
||||
|
||||
**Solution**: `UmbracoSchemaIdGenerator` adds "Model" suffix to all schema names.
|
||||
**Solution**: Add "Model" suffix (OpenApi/SchemaIdHandler.cs:24-29)
|
||||
|
||||
### Generic Type Handling
|
||||
|
||||
**Issue**: `PagedViewModel<T>` needs flattened schema name.
|
||||
|
||||
**Solution**: `UmbracoSchemaIdGenerator.Generate()` flattens generic types:
|
||||
- `PagedViewModel<RelationItemViewModel>` becomes `PagedRelationItemModel`
|
||||
**Solution** (OpenApi/SchemaIdHandler.cs:41-50):
|
||||
```csharp
|
||||
private string HandleGenerics(string name, Type type)
|
||||
{
|
||||
if (!type.IsGenericType)
|
||||
return name;
|
||||
|
||||
// use attribute custom name or append the generic type names
|
||||
// turns "PagedViewModel<RelationItemViewModel>" into "PagedRelationItem"
|
||||
return $"{name}{string.Join(string.Empty, type.GenericTypeArguments.Select(SanitizedTypeName))}";
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Extending This Library
|
||||
|
||||
### Adding Custom OpenAPI Transformers
|
||||
### Adding a Custom OpenAPI Handler
|
||||
|
||||
OpenAPI transformers are scoped per-document. To customize a document, implement `IOpenApiDocumentTransformer`, `IOpenApiOperationTransformer`, or `IOpenApiSchemaTransformer` and register with your OpenAPI options.
|
||||
1. **Implement interface**:
|
||||
```csharp
|
||||
public class MySchemaIdHandler : SchemaIdHandler
|
||||
{
|
||||
public override bool CanHandle(Type type)
|
||||
=> type.Namespace?.StartsWith("MyProject") is true;
|
||||
|
||||
For schema ID generation, use the static `UmbracoSchemaIdGenerator.Generate(Type)` method.
|
||||
public override string Handle(Type type)
|
||||
=> $"My{base.Handle(type)}";
|
||||
}
|
||||
```
|
||||
|
||||
2. **Register in consuming API**:
|
||||
```csharp
|
||||
builder.Services.AddSingleton<ISchemaIdHandler, MySchemaIdHandler>();
|
||||
```
|
||||
|
||||
**Note**: Handlers registered later take precedence in the selector.
|
||||
|
||||
### Customizing Problem Details
|
||||
|
||||
@@ -240,9 +269,13 @@ return BadRequest(problemDetails);
|
||||
|
||||
## 8. Project-Specific Notes
|
||||
|
||||
### Per-Document Transformer Scoping
|
||||
### Why Virtual Handlers?
|
||||
|
||||
With Microsoft.AspNetCore.OpenApi, transformers are configured per OpenAPI document. This means custom transformers only apply to the documents they're registered with, not globally. Each API (Management, Delivery) configures its own transformers via `ConfigureUmbracoOpenApiOptionsBase` subclasses.
|
||||
**Decision**: Make `SchemaIdHandler`, `OperationIdHandler`, etc. virtual.
|
||||
|
||||
**Why**: Management API and Delivery API have different schema ID requirements. Virtual methods allow override without rewriting the entire handler.
|
||||
|
||||
**Example**: Management API might prefix all schemas with "Management", Delivery API with "Delivery".
|
||||
|
||||
### Performance: Subtype Caching
|
||||
|
||||
@@ -271,13 +304,9 @@ With Microsoft.AspNetCore.OpenApi, transformers are configured per OpenAPI docum
|
||||
- Version: See `Directory.Packages.props`
|
||||
- Uses ASP.NET Core Data Protection for token encryption
|
||||
|
||||
**Microsoft.AspNetCore.OpenApi**:
|
||||
- OpenAPI 3.1.1 document generation
|
||||
- Custom transformers: `SchemaIdTransformer`, `OperationIdTransformer`, `MimeTypeDocumentTransformer`, `ServerTransformer`
|
||||
|
||||
**Swashbuckle.AspNetCore.SwaggerUI**:
|
||||
- Swagger UI for browsing and testing API endpoints
|
||||
- Accessed at `/umbraco/openapi/`
|
||||
**Swashbuckle**:
|
||||
- OpenAPI 3.0 document generation
|
||||
- Custom filters: `EnumSchemaFilter`, `MimeTypeDocumentFilter`, `RemoveSecuritySchemesDocumentFilter`
|
||||
|
||||
**Asp.Versioning**:
|
||||
- API versioning via `ApiVersion` attribute
|
||||
@@ -289,7 +318,7 @@ With Microsoft.AspNetCore.OpenApi, transformers are configured per OpenAPI docum
|
||||
|
||||
### Usage Pattern
|
||||
|
||||
Consuming APIs call `builder.AddUmbracoOpenApi().AddUmbracoOpenIddict()`
|
||||
Consuming APIs call `builder.AddUmbracoApiOpenApiUI().AddUmbracoOpenIddict()`
|
||||
|
||||
---
|
||||
|
||||
@@ -317,8 +346,7 @@ dotnet list src/Umbraco.Cms.Api.Common/Umbraco.Cms.Api.Common.csproj package --v
|
||||
| Class | Purpose | File |
|
||||
|-------|---------|------|
|
||||
| `ProblemDetailsBuilder` | Build RFC 7807 error responses | Builders/ProblemDetailsBuilder.cs |
|
||||
| `UmbracoSchemaIdGenerator` | Generate OpenAPI schema IDs | OpenApi/UmbracoSchemaIdGenerator.cs |
|
||||
| `UmbracoOperationIdTransformer` | Generate operation IDs | OpenApi/UmbracoOperationIdTransformer.cs |
|
||||
| `SchemaIdHandler` | Generate OpenAPI schema IDs | OpenApi/SchemaIdHandler.cs |
|
||||
| `UmbracoJsonTypeInfoResolver` | Polymorphic JSON serialization | Serialization/UmbracoJsonTypeInfoResolver.cs |
|
||||
| `UmbracoBuilderAuthExtensions` | Configure OpenIddict | DependencyInjection/UmbracoBuilderAuthExtensions.cs |
|
||||
| `HideBackOfficeTokensHandler` | Secure cookie-based token storage | DependencyInjection/HideBackOfficeTokensHandler.cs |
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
using System.Reflection;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc.Abstractions;
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the OpenAPI options for the Default API.
|
||||
/// </summary>
|
||||
internal class ConfigureDefaultApiOptions : ConfigureUmbracoOpenApiOptionsBase
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override string ApiName => DefaultApiConfiguration.ApiName;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ApiTitle => "Default API";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ApiVersion => "Latest";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ApiDescription => "All endpoints not defined under specific APIs";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override bool ShouldInclude(ApiDescription apiDescription)
|
||||
{
|
||||
// Exclude controllers with ExcludeFromDefaultOpenApiDocumentAttribute
|
||||
if (apiDescription.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor
|
||||
&& controllerActionDescriptor.ControllerTypeInfo.GetCustomAttribute<ExcludeFromDefaultOpenApiDocumentAttribute>() is not null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Include if explicitly mapped to this document
|
||||
if (base.ShouldInclude(apiDescription))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Include endpoints not explicitly assigned to another document
|
||||
ApiVersionMetadata apiVersionMetadata = apiDescription.ActionDescriptor.ApiVersionMetadata;
|
||||
return string.IsNullOrEmpty(apiVersionMetadata.Name);
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc.Abstractions;
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using Umbraco.Cms.Api.Common.OpenApi;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for configuring OpenAPI options for Umbraco APIs.
|
||||
/// </summary>
|
||||
internal abstract class ConfigureUmbracoOpenApiOptionsBase : IConfigureNamedOptions<OpenApiOptions>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the name/identifier of the API to configure.
|
||||
/// </summary>
|
||||
protected abstract string ApiName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name/identifier of the API to configure.
|
||||
/// </summary>
|
||||
protected abstract string ApiTitle { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the version of the API to configure.
|
||||
/// </summary>
|
||||
protected abstract string ApiVersion { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the description of the API to configure.
|
||||
/// </summary>
|
||||
protected abstract string ApiDescription { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Configure(OpenApiOptions options) => Configure(Options.DefaultName, options);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Configure(string? name, OpenApiOptions options)
|
||||
{
|
||||
if (name != ApiName)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ConfigureOpenApi(options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure the OpenAPI options for the specified API.
|
||||
/// </summary>
|
||||
/// <param name="options">The <see cref="OpenApiOptions"/> instance to configure.</param>
|
||||
protected virtual void ConfigureOpenApi(OpenApiOptions options)
|
||||
{
|
||||
options.AddDocumentTransformer((document, _, _) =>
|
||||
{
|
||||
document.Info = new OpenApiInfo
|
||||
{
|
||||
Title = ApiTitle,
|
||||
Version = ApiVersion,
|
||||
Description = ApiDescription,
|
||||
};
|
||||
document.Servers?.Clear();
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
options.ShouldInclude = ShouldInclude;
|
||||
options.CreateSchemaReferenceId = UmbracoSchemaIdGenerator.CreateSchemaReferenceId;
|
||||
|
||||
options.AddOperationTransformer<UmbracoOperationIdTransformer>();
|
||||
|
||||
// Tag actions by group name and cleanup unused tags (caused by the tag changes)
|
||||
options
|
||||
.AddOperationTransformer<TagActionsByGroupNameTransformer>()
|
||||
.AddDocumentTransformer<TagActionsByGroupNameTransformer>()
|
||||
.AddDocumentTransformer<SortTagsAndPathsTransformer>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the specified API description should be included in this OpenAPI document.
|
||||
/// </summary>
|
||||
/// <param name="apiDescription">The API description to evaluate.</param>
|
||||
/// <returns><c>true</c> if the endpoint should be included; otherwise, <c>false</c>.</returns>
|
||||
protected virtual bool ShouldInclude(ApiDescription apiDescription)
|
||||
{
|
||||
if (apiDescription.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor
|
||||
&& controllerActionDescriptor.HasMapToApiAttribute(ApiName))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
ApiVersionMetadata apiVersionMetadata = apiDescription.ActionDescriptor.ApiVersionMetadata;
|
||||
return apiVersionMetadata.Name == ApiName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Cms.Api.Common.OpenApi;
|
||||
using Umbraco.Cms.Core.DependencyInjection;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures Swagger/OpenAPI generation options for Umbraco APIs.
|
||||
/// </summary>
|
||||
public class ConfigureUmbracoSwaggerGenOptions : IConfigureOptions<SwaggerGenOptions>
|
||||
{
|
||||
private readonly IOperationIdSelector _operationIdSelector;
|
||||
private readonly ISchemaIdSelector _schemaIdSelector;
|
||||
private readonly ISubTypesSelector _subTypesSelector;
|
||||
private readonly IDocumentInclusionSelector _documentInclusionSelector;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConfigureUmbracoSwaggerGenOptions"/> class.
|
||||
/// </summary>
|
||||
/// <param name="operationIdSelector">The operation ID selector.</param>
|
||||
/// <param name="schemaIdSelector">The schema ID selector.</param>
|
||||
/// <param name="subTypesSelector">The sub-types selector for polymorphism support.</param>
|
||||
/// <param name="documentInclusionSelector">The document inclusion selector.</param>
|
||||
public ConfigureUmbracoSwaggerGenOptions(
|
||||
IOperationIdSelector operationIdSelector,
|
||||
ISchemaIdSelector schemaIdSelector,
|
||||
ISubTypesSelector subTypesSelector,
|
||||
IDocumentInclusionSelector documentInclusionSelector)
|
||||
{
|
||||
_operationIdSelector = operationIdSelector;
|
||||
_schemaIdSelector = schemaIdSelector;
|
||||
_subTypesSelector = subTypesSelector;
|
||||
_documentInclusionSelector = documentInclusionSelector;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConfigureUmbracoSwaggerGenOptions"/> class.
|
||||
/// </summary>
|
||||
/// <param name="operationIdSelector">The operation ID selector.</param>
|
||||
/// <param name="schemaIdSelector">The schema ID selector.</param>
|
||||
/// <param name="subTypesSelector">The sub-types selector for polymorphism support.</param>
|
||||
[Obsolete("Please use the constructor with all parameters. Scheduled for removal in Umbraco 19.")]
|
||||
public ConfigureUmbracoSwaggerGenOptions(
|
||||
IOperationIdSelector operationIdSelector,
|
||||
ISchemaIdSelector schemaIdSelector,
|
||||
ISubTypesSelector subTypesSelector)
|
||||
: this(
|
||||
operationIdSelector,
|
||||
schemaIdSelector,
|
||||
subTypesSelector,
|
||||
StaticServiceProvider.Instance.GetRequiredService<IDocumentInclusionSelector>())
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Configure(SwaggerGenOptions swaggerGenOptions)
|
||||
{
|
||||
swaggerGenOptions.SwaggerDoc(
|
||||
DefaultApiConfiguration.ApiName,
|
||||
new OpenApiInfo
|
||||
{
|
||||
Title = "Default API",
|
||||
Version = "Latest",
|
||||
Description = "All endpoints not defined under specific APIs",
|
||||
});
|
||||
|
||||
swaggerGenOptions.CustomOperationIds(description => _operationIdSelector.OperationId(description));
|
||||
swaggerGenOptions.DocInclusionPredicate(_documentInclusionSelector.Include);
|
||||
swaggerGenOptions.TagActionsBy(api =>
|
||||
api.GroupName is null
|
||||
? []
|
||||
: new[] { api.GroupName });
|
||||
swaggerGenOptions.OrderActionsBy(ActionOrderBy);
|
||||
swaggerGenOptions.SchemaFilter<EnumSchemaFilter>();
|
||||
swaggerGenOptions.CustomSchemaIds(_schemaIdSelector.SchemaId);
|
||||
swaggerGenOptions.SelectSubTypesUsing(_subTypesSelector.SubTypes);
|
||||
swaggerGenOptions.SupportNonNullableReferenceTypes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a sort key for API actions.
|
||||
/// </summary>
|
||||
/// <param name="apiDesc">The API description.</param>
|
||||
/// <returns>A string used to sort API operations in the documentation.</returns>
|
||||
/// <remarks>
|
||||
/// See https://github.com/domaindrivendev/Swashbuckle.AspNetCore#change-operation-sort-order-eg-for-ui-sorting.
|
||||
/// </remarks>
|
||||
private static string ActionOrderBy(ApiDescription apiDesc)
|
||||
=> $"{apiDesc.GroupName}_{apiDesc.ActionDescriptor.AttributeRouteInfo?.Template ?? apiDesc.ActionDescriptor.RouteValues["controller"]}_{(apiDesc.ActionDescriptor.RouteValues.TryGetValue("action", out var action) ? action : null)}_{apiDesc.HttpMethod}";
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for replacing the internal Microsoft.AspNetCore.OpenApi schema service registration.
|
||||
/// </summary>
|
||||
internal static class OpenApiSchemaServiceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// The full name of the internal Microsoft type whose registration is replaced.
|
||||
/// Used for a stringly-typed <see cref="ServiceDescriptor"/> lookup because the type is not publicly accessible.
|
||||
/// </summary>
|
||||
internal const string OpenApiSchemaServiceFullName = "Microsoft.AspNetCore.OpenApi.OpenApiSchemaService";
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the internal Microsoft <c>OpenApiSchemaService</c> registration for the specified document so that schema
|
||||
/// generation uses the named <see cref="JsonOptions"/> rather than the default HTTP JSON options.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection.</param>
|
||||
/// <param name="documentName">The OpenAPI document key (matches the keyed singleton registered by <c>AddOpenApi(documentName)</c>).</param>
|
||||
/// <param name="jsonOptionsName">The named <see cref="JsonOptions"/> to use during schema generation for this document.</param>
|
||||
/// <returns>The same <see cref="IServiceCollection"/> for chaining.</returns>
|
||||
/// <remarks>
|
||||
/// Workaround for <see href="https://github.com/dotnet/aspnetcore/issues/66340">dotnet/aspnetcore#66340</see>.
|
||||
/// </remarks>
|
||||
public static IServiceCollection ReplaceOpenApiSchemaService(
|
||||
this IServiceCollection services,
|
||||
string documentName,
|
||||
string jsonOptionsName)
|
||||
=> services.ReplaceOpenApiSchemaService(
|
||||
documentName,
|
||||
sp => sp.GetRequiredService<IOptionsMonitor<JsonOptions>>().Get(jsonOptionsName));
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the internal Microsoft <c>OpenApiSchemaService</c> registration for the specified document so that schema
|
||||
/// generation uses the <see cref="JsonOptions"/> instance produced by the supplied factory. Use this overload when
|
||||
/// the options need to be resolved from the service provider, computed at the last moment, or built in a way that
|
||||
/// doesn't fit the named-options lookup.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection.</param>
|
||||
/// <param name="documentName">The OpenAPI document key.</param>
|
||||
/// <param name="jsonOptionsFactory">Factory invoked when the schema service is first resolved. Receives the resolving <see cref="IServiceProvider"/> and returns the <see cref="JsonOptions"/> to use.</param>
|
||||
/// <returns>The same <see cref="IServiceCollection"/> for chaining.</returns>
|
||||
/// <remarks>
|
||||
/// Workaround for <see href="https://github.com/dotnet/aspnetcore/issues/66340">dotnet/aspnetcore#66340</see>.
|
||||
/// </remarks>
|
||||
public static IServiceCollection ReplaceOpenApiSchemaService(
|
||||
this IServiceCollection services,
|
||||
string documentName,
|
||||
Func<IServiceProvider, JsonOptions> jsonOptionsFactory)
|
||||
{
|
||||
ServiceDescriptor descriptor = services.FirstOrDefault(sd =>
|
||||
sd.ServiceType.FullName == OpenApiSchemaServiceFullName
|
||||
&& Equals(sd.ServiceKey, documentName))
|
||||
?? throw new InvalidOperationException(
|
||||
$"Could not find a registration for {OpenApiSchemaServiceFullName} keyed with '{documentName}'. "
|
||||
+ $"Ensure AddOpenApi(\"{documentName}\") has been called before {nameof(ReplaceOpenApiSchemaService)}, "
|
||||
+ "or check whether the internal Microsoft.AspNetCore.OpenApi registration shape has changed.");
|
||||
|
||||
services.Remove(descriptor);
|
||||
services.AddKeyedSingleton(
|
||||
descriptor.ServiceType,
|
||||
documentName,
|
||||
(sp, key) => ActivatorUtilities.CreateInstance(
|
||||
sp,
|
||||
descriptor.ServiceType,
|
||||
key,
|
||||
Options.Create(jsonOptionsFactory(sp))));
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Swashbuckle.AspNetCore.SwaggerUI;
|
||||
using Umbraco.Cms.Api.Common.OpenApi;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for <see cref="IServiceCollection"/> to configure OpenAPI services.
|
||||
/// </summary>
|
||||
public static class OpenApiServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds an OpenAPI document to the OpenAPI UI document selector dropdown.
|
||||
/// </summary>
|
||||
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
|
||||
/// <param name="documentName">The name/identifier of the OpenAPI document.</param>
|
||||
/// <param name="documentTitle">The title to display in the UI dropdown. Defaults to <paramref name="documentName"/> if not specified.</param>
|
||||
/// <returns>The <see cref="IServiceCollection"/> instance.</returns>
|
||||
public static IServiceCollection AddOpenApiDocumentToUi(
|
||||
this IServiceCollection services,
|
||||
string documentName,
|
||||
string? documentTitle = null)
|
||||
=> services.AddOpenApiDocumentToUi(documentName, () => documentTitle);
|
||||
|
||||
/// <summary>
|
||||
/// Adds an OpenAPI document to the OpenAPI UI document selector dropdown, resolving the title lazily so
|
||||
/// callers (such as builder-pattern helpers) can defer it until SwaggerUI options are resolved.
|
||||
/// </summary>
|
||||
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
|
||||
/// <param name="documentName">The name/identifier of the OpenAPI document.</param>
|
||||
/// <param name="documentTitleFactory">Factory invoked when SwaggerUI options are resolved. Returning <c>null</c> falls back to <paramref name="documentName"/>.</param>
|
||||
/// <returns>The <see cref="IServiceCollection"/> instance.</returns>
|
||||
internal static IServiceCollection AddOpenApiDocumentToUi(
|
||||
this IServiceCollection services,
|
||||
string documentName,
|
||||
Func<string?> documentTitleFactory)
|
||||
{
|
||||
services.AddOptions<SwaggerUIOptions>()
|
||||
.Configure<IOptions<UmbracoOpenApiOptions>>((swaggerUiOptions, openApiOptions) =>
|
||||
{
|
||||
var openApiRoute = openApiOptions.Value.RouteTemplate.Replace("{documentName}", documentName).EnsureStartsWith("/");
|
||||
swaggerUiOptions.SwaggerEndpoint(openApiRoute, documentTitleFactory() ?? documentName);
|
||||
swaggerUiOptions.ConfigObject.Urls = swaggerUiOptions.ConfigObject.Urls.OrderBy(x => x.Name);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Umbraco.Cms.Api.Common.Configuration;
|
||||
using Umbraco.Cms.Api.Common.OpenApi;
|
||||
using Umbraco.Cms.Api.Common.Serialization;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.DependencyInjection;
|
||||
using Umbraco.Cms.Core.Hosting;
|
||||
using Umbraco.Cms.Web.Common.ApplicationBuilder;
|
||||
using IHostingEnvironment = Umbraco.Cms.Core.Hosting.IHostingEnvironment;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.DependencyInjection;
|
||||
|
||||
@@ -21,52 +16,26 @@ public static class UmbracoBuilderApiExtensions
|
||||
/// Adds Umbraco API OpenAPI/Swagger UI services to the builder.
|
||||
/// </summary>
|
||||
/// <param name="builder">The Umbraco builder.</param>
|
||||
internal static void AddUmbracoOpenApi(this IUmbracoBuilder builder)
|
||||
/// <returns>The Umbraco builder for method chaining.</returns>
|
||||
public static IUmbracoBuilder AddUmbracoApiOpenApiUI(this IUmbracoBuilder builder)
|
||||
{
|
||||
if (builder.Services.Any(x => !x.IsKeyedService && x.ImplementationType == typeof(UmbracoJsonTypeInfoResolver)))
|
||||
if (builder.Services.Any(x => !x.IsKeyedService && x.ImplementationType == typeof(OperationIdSelector)))
|
||||
{
|
||||
return;
|
||||
return builder;
|
||||
}
|
||||
|
||||
builder.Services.AddOptions<UmbracoOpenApiOptions>()
|
||||
.Configure<IHostingEnvironment, IWebHostEnvironment>((options, hostingEnv, webHostEnv) =>
|
||||
{
|
||||
options.Enabled = webHostEnv.IsProduction() is false;
|
||||
var backOfficePath = hostingEnv.GetBackOfficePath().TrimStart(Constants.CharArrays.ForwardSlash);
|
||||
options.RouteTemplate = $"{backOfficePath}/openapi/{{documentName}}.json";
|
||||
options.UiRoutePrefix = $"{backOfficePath}/openapi";
|
||||
});
|
||||
builder.AddUmbracoOpenApiDocument<ConfigureDefaultApiOptions>(DefaultApiConfiguration.ApiName, "Default API");
|
||||
builder.Services.AddSwaggerGen();
|
||||
builder.Services.ConfigureOptions<ConfigureUmbracoSwaggerGenOptions>();
|
||||
builder.Services.AddSingleton<IUmbracoJsonTypeInfoResolver, UmbracoJsonTypeInfoResolver>();
|
||||
builder.Services.Configure<UmbracoPipelineOptions>(options => options.AddFilter(new OpenApiRouteTemplatePipelineFilter("UmbracoApiCommon")));
|
||||
}
|
||||
builder.Services.AddSingleton<IOperationIdSelector, OperationIdSelector>();
|
||||
builder.Services.AddSingleton<IOperationIdHandler, OperationIdHandler>();
|
||||
builder.Services.AddSingleton<ISchemaIdSelector, SchemaIdSelector>();
|
||||
builder.Services.AddSingleton<ISchemaIdHandler, SchemaIdHandler>();
|
||||
builder.Services.AddSingleton<ISubTypesSelector, SubTypesSelector>();
|
||||
builder.Services.AddSingleton<ISubTypesHandler, SubTypesHandler>();
|
||||
builder.Services.AddSingleton<IDocumentInclusionSelector, DocumentInclusionSelector>();
|
||||
builder.Services.Configure<UmbracoPipelineOptions>(options => options.AddFilter(new SwaggerRouteTemplatePipelineFilter("UmbracoApiCommon")));
|
||||
|
||||
/// <summary>
|
||||
/// Adds and configures an Umbraco OpenAPI document with shared transformers.
|
||||
/// </summary>
|
||||
/// <param name="builder">The Umbraco builder.</param>
|
||||
/// <param name="apiName">The name/identifier of the API.</param>
|
||||
/// <param name="apiTitle">The title of the API.</param>
|
||||
/// <param name="jsonOptionsName">
|
||||
/// Optional named <c>JsonOptions</c> to use for schema generation instead of the default HTTP JSON options.
|
||||
/// When specified, replaces the internal <c>OpenApiSchemaService</c> registration for this document.
|
||||
/// </param>
|
||||
/// <typeparam name="TConfigureOptions">The type used to configure the OpenAPI options.</typeparam>
|
||||
internal static void AddUmbracoOpenApiDocument<TConfigureOptions>(
|
||||
this IUmbracoBuilder builder,
|
||||
string apiName,
|
||||
string apiTitle,
|
||||
string? jsonOptionsName = null)
|
||||
where TConfigureOptions : ConfigureUmbracoOpenApiOptionsBase
|
||||
{
|
||||
apiName = apiName.ToLowerInvariant();
|
||||
builder.Services.AddOpenApi(apiName);
|
||||
builder.Services.ConfigureOptions<TConfigureOptions>();
|
||||
builder.Services.AddOpenApiDocumentToUi(apiName, apiTitle);
|
||||
|
||||
if (jsonOptionsName is not null)
|
||||
{
|
||||
builder.Services.ReplaceOpenApiSchemaService(apiName, jsonOptionsName);
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http.Json;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Umbraco.Cms.Api.Common.Attributes;
|
||||
using Umbraco.Cms.Api.Common.DependencyInjection;
|
||||
using Umbraco.Cms.Core.DependencyInjection;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Fluent builder for configuring a custom OpenAPI document.
|
||||
/// </summary>
|
||||
public sealed class BackOfficeOpenApiDocumentBuilder
|
||||
{
|
||||
private readonly List<Action<OpenApiOptions>> _configurations = [];
|
||||
|
||||
private string? _title;
|
||||
private string? _uiTitle;
|
||||
private bool _includedInUi = true;
|
||||
private Func<IServiceProvider, JsonOptions>? _httpJsonOptionsFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BackOfficeOpenApiDocumentBuilder"/> class.
|
||||
/// </summary>
|
||||
/// <param name="documentName">The name of the OpenAPI document being configured.</param>
|
||||
internal BackOfficeOpenApiDocumentBuilder(string documentName)
|
||||
=> DocumentName = documentName;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the OpenAPI document being configured.
|
||||
/// </summary>
|
||||
public string DocumentName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Sets the document's <c>Info.Title</c>. Also used as the UI dropdown label unless overridden via
|
||||
/// <see cref="WithUiTitle"/>.
|
||||
/// </summary>
|
||||
/// <param name="title">The title to display.</param>
|
||||
/// <returns>The same builder for chaining.</returns>
|
||||
public BackOfficeOpenApiDocumentBuilder WithTitle(string title)
|
||||
{
|
||||
_title = title;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the UI dropdown label for this document.
|
||||
/// </summary>
|
||||
/// <param name="uiTitle">The label to display.</param>
|
||||
/// <returns>The same builder for chaining.</returns>
|
||||
public BackOfficeOpenApiDocumentBuilder WithUiTitle(string uiTitle)
|
||||
{
|
||||
_uiTitle = uiTitle;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Excludes this document from the UI dropdown.
|
||||
/// </summary>
|
||||
/// <returns>The same builder for chaining.</returns>
|
||||
public BackOfficeOpenApiDocumentBuilder ExcludeFromUi()
|
||||
{
|
||||
_includedInUi = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds an <see cref="OpenApiOptions"/> configuration callback. Multiple calls compose.
|
||||
/// </summary>
|
||||
/// <param name="configure">Callback to configure the options.</param>
|
||||
/// <returns>The same builder for chaining.</returns>
|
||||
public BackOfficeOpenApiDocumentBuilder ConfigureOpenApiOptions(Action<OpenApiOptions> configure)
|
||||
{
|
||||
_configurations.Add(configure);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the named <see cref="JsonOptions">Microsoft.AspNetCore.Http.Json.JsonOptions</see> used when
|
||||
/// generating this document's schema. Use this to match the serialization conventions of the API
|
||||
/// endpoints the document describes.
|
||||
/// </summary>
|
||||
/// <param name="jsonOptionsName">The name of the registered HTTP <see cref="JsonOptions"/> to apply.</param>
|
||||
/// <returns>The same builder for chaining.</returns>
|
||||
public BackOfficeOpenApiDocumentBuilder WithJsonOptions(string jsonOptionsName)
|
||||
=> WithJsonOptions(sp => sp.GetRequiredService<IOptionsMonitor<JsonOptions>>().Get(jsonOptionsName));
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <see cref="JsonOptions">Microsoft.AspNetCore.Http.Json.JsonOptions</see> used when
|
||||
/// generating this document's schema. Use this to match the serialization conventions of the API
|
||||
/// endpoints the document describes.
|
||||
/// </summary>
|
||||
/// <param name="jsonOptions">The HTTP JSON options to apply.</param>
|
||||
/// <returns>The same builder for chaining.</returns>
|
||||
public BackOfficeOpenApiDocumentBuilder WithJsonOptions(JsonOptions jsonOptions)
|
||||
=> WithJsonOptions(_ => jsonOptions);
|
||||
|
||||
/// <summary>
|
||||
/// Sets a factory that produces the <see cref="JsonOptions">Microsoft.AspNetCore.Http.Json.JsonOptions</see>
|
||||
/// used when generating this document's schema. Use this to match the serialization conventions of the
|
||||
/// API endpoints the document describes.
|
||||
/// </summary>
|
||||
/// <param name="jsonOptionsFactory">Factory invoked when the schema service is first resolved.</param>
|
||||
/// <returns>The same builder for chaining.</returns>
|
||||
public BackOfficeOpenApiDocumentBuilder WithJsonOptions(Func<IServiceProvider, JsonOptions> jsonOptionsFactory)
|
||||
{
|
||||
_httpJsonOptionsFactory = jsonOptionsFactory;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the accumulated configuration to the supplied <see cref="IUmbracoBuilder"/>'s service
|
||||
/// collection. Called by <c>AddBackOfficeOpenApiDocument</c> once the user-supplied callback returns.
|
||||
/// </summary>
|
||||
/// <param name="builder">The Umbraco builder to register services against.</param>
|
||||
internal void Build(IUmbracoBuilder builder)
|
||||
{
|
||||
// AddOpenApi lowercases the document name when registering its keyed services (https://github.com/dotnet/aspnetcore/blob/v10.0.9/src/OpenApi/src/Extensions/OpenApiServiceCollectionExtensions.cs#L64),
|
||||
// so we must normalise here to keep AddOpenApiDocumentToUi and ReplaceOpenApiSchemaService in sync.
|
||||
string lowercasedDocumentName = DocumentName.ToLowerInvariant();
|
||||
|
||||
builder.Services.AddOpenApi(
|
||||
lowercasedDocumentName,
|
||||
options =>
|
||||
{
|
||||
// ShouldInclude matches [MapToApi] case-insensitively to align with how documents are registered.
|
||||
options.ShouldInclude = apiDescription =>
|
||||
apiDescription.ActionDescriptor.EndpointMetadata
|
||||
?.OfType<MapToApiAttribute>()
|
||||
.Any(a => a.ApiName.Equals(DocumentName, StringComparison.OrdinalIgnoreCase))
|
||||
?? false;
|
||||
|
||||
options.CreateSchemaReferenceId = UmbracoSchemaIdGenerator.CreateSchemaReferenceId;
|
||||
|
||||
if (_title is not null)
|
||||
{
|
||||
options.AddDocumentTransformer((document, _, _) =>
|
||||
{
|
||||
document.Info.Title = _title;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
}
|
||||
|
||||
// Generate operation IDs using Umbraco's naming conventions.
|
||||
options.AddOperationTransformer<UmbracoOperationIdTransformer>();
|
||||
|
||||
// Trim redundant JSON-equivalent MIME types (e.g. text/json, application/*+json, text/plain)
|
||||
// that ASP.NET Core adds alongside application/json.
|
||||
options.AddOperationTransformer<MimeTypesTransformer>();
|
||||
|
||||
// Mark non-nullable properties as required so generated SDKs reflect the C# nullability.
|
||||
options.AddSchemaTransformer<RequireNonNullablePropertiesSchemaTransformer>();
|
||||
|
||||
// Tag actions by group name and cleanup unused tags (caused by the tag changes).
|
||||
options
|
||||
.AddOperationTransformer<TagActionsByGroupNameTransformer>()
|
||||
.AddDocumentTransformer<TagActionsByGroupNameTransformer>()
|
||||
.AddDocumentTransformer<SortTagsAndPathsTransformer>();
|
||||
|
||||
foreach (Action<OpenApiOptions> configure in _configurations)
|
||||
{
|
||||
configure(options);
|
||||
}
|
||||
});
|
||||
|
||||
if (_includedInUi)
|
||||
{
|
||||
builder.Services.AddOpenApiDocumentToUi(lowercasedDocumentName, _uiTitle ?? _title ?? DocumentName);
|
||||
}
|
||||
|
||||
if (_httpJsonOptionsFactory is not null)
|
||||
{
|
||||
builder.Services.ReplaceOpenApiSchemaService(lowercasedDocumentName, _httpJsonOptionsFactory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc.Abstractions;
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Umbraco.Cms.Api.Common.Configuration;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether an API description should be included in a specific documentation set based on the document name
|
||||
/// and API metadata.
|
||||
/// </summary>
|
||||
public class DocumentInclusionSelector : IDocumentInclusionSelector
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public bool Include(string documentName, ApiDescription apiDescription)
|
||||
{
|
||||
if (apiDescription.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor
|
||||
&& controllerActionDescriptor.HasMapToApiAttribute(documentName))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
ApiVersionMetadata apiVersionMetadata = apiDescription.ActionDescriptor.GetApiVersionMetadata();
|
||||
return apiVersionMetadata.Name == documentName
|
||||
|| (string.IsNullOrEmpty(apiVersionMetadata.Name) && documentName == DefaultApiConfiguration.ApiName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// A schema filter that converts enum schemas to string type with enum member names.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This filter ensures enums are represented as strings in the OpenAPI schema,
|
||||
/// using <see cref="EnumMemberAttribute"/> values when available.
|
||||
/// </remarks>
|
||||
public class EnumSchemaFilter : ISchemaFilter
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Apply(IOpenApiSchema model, SchemaFilterContext context)
|
||||
{
|
||||
if (model is not OpenApiSchema schema || context.Type.IsEnum is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
schema.Type = JsonSchemaType.String;
|
||||
schema.Format = null;
|
||||
schema.Enum = new List<JsonNode>();
|
||||
foreach (var name in Enum.GetNames(context.Type))
|
||||
{
|
||||
var actualName = context.Type.GetField(name)?.GetCustomAttribute<EnumMemberAttribute>()?.Value ?? name;
|
||||
schema.Enum.Add(actualName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Excludes the controller from the default OpenAPI document.
|
||||
/// Use this when you have a custom OpenAPI document for your API.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class)]
|
||||
public sealed class ExcludeFromDefaultOpenApiDocumentAttribute : Attribute
|
||||
{
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
using System.IO.Pipelines;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Transformer to fix file return types in OpenAPI schema.
|
||||
/// </summary>
|
||||
/// <remarks>Can be removed once https://github.com/dotnet/aspnetcore/pull/63504 and
|
||||
/// https://github.com/dotnet/aspnetcore/pull/64562 are released.</remarks>
|
||||
internal class FixFileReturnTypesTransformer : IOpenApiSchemaTransformer
|
||||
{
|
||||
private static readonly Type[] _binaryStringTypes =
|
||||
[
|
||||
typeof(IFormFile),
|
||||
typeof(FileResult),
|
||||
typeof(Stream),
|
||||
typeof(PipeReader),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task TransformAsync(
|
||||
OpenApiSchema schema,
|
||||
OpenApiSchemaTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (_binaryStringTypes.Any(possibleBaseType => possibleBaseType.IsAssignableFrom(context.JsonTypeInfo.Type)) is false)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
// Clear all properties
|
||||
schema.Properties?.Clear();
|
||||
schema.Required?.Clear();
|
||||
|
||||
// Make it an inline schema
|
||||
schema.Metadata?.Remove("x-schema-id");
|
||||
|
||||
// Set type to string with binary format
|
||||
schema.Type = JsonSchemaType.String;
|
||||
schema.Format = "binary";
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a method that determines whether a given API description should be included in a specific documentation
|
||||
/// document.
|
||||
/// </summary>
|
||||
public interface IDocumentInclusionSelector
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the specified API description should be included in the generated documentation for the given
|
||||
/// document name.
|
||||
/// </summary>
|
||||
/// <param name="documentName">The name of the documentation document being generated.</param>
|
||||
/// <param name="apiDescription">The API description to evaluate for inclusion.</param>
|
||||
/// <returns>true if the API description should be included in the documentation; otherwise, false.</returns>
|
||||
bool Include(string documentName, ApiDescription apiDescription);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a handler for generating OpenAPI operation IDs.
|
||||
/// </summary>
|
||||
public interface IOperationIdHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether this handler can generate an operation ID for the specified API description.
|
||||
/// </summary>
|
||||
/// <param name="apiDescription">The API description to check.</param>
|
||||
/// <returns><c>true</c> if this handler can handle the API description; otherwise, <c>false</c>.</returns>
|
||||
bool CanHandle(ApiDescription apiDescription);
|
||||
|
||||
/// <summary>
|
||||
/// Generates an operation ID for the specified API description.
|
||||
/// </summary>
|
||||
/// <param name="apiDescription">The API description to generate an operation ID for.</param>
|
||||
/// <returns>The generated operation ID.</returns>
|
||||
string Handle(ApiDescription apiDescription);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a selector for choosing operation IDs from registered handlers.
|
||||
/// </summary>
|
||||
public interface IOperationIdSelector
|
||||
{
|
||||
/// <summary>
|
||||
/// Selects an operation ID for the specified API description.
|
||||
/// </summary>
|
||||
/// <param name="apiDescription">The API description to generate an operation ID for.</param>
|
||||
/// <returns>The operation ID, or <c>null</c> if none could be determined.</returns>
|
||||
string? OperationId(ApiDescription apiDescription);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a handler for generating OpenAPI schema IDs.
|
||||
/// </summary>
|
||||
public interface ISchemaIdHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether this handler can generate a schema ID for the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to check.</param>
|
||||
/// <returns><c>true</c> if this handler can handle the type; otherwise, <c>false</c>.</returns>
|
||||
bool CanHandle(Type type);
|
||||
|
||||
/// <summary>
|
||||
/// Generates a schema ID for the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a schema ID for.</param>
|
||||
/// <returns>The generated schema ID.</returns>
|
||||
string Handle(Type type);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a selector for choosing schema IDs from registered handlers.
|
||||
/// </summary>
|
||||
public interface ISchemaIdSelector
|
||||
{
|
||||
/// <summary>
|
||||
/// Selects a schema ID for the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a schema ID for.</param>
|
||||
/// <returns>The schema ID.</returns>
|
||||
string SchemaId(Type type);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a handler for discovering sub-types for polymorphic OpenAPI schemas.
|
||||
/// </summary>
|
||||
public interface ISubTypesHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether this handler can discover sub-types for the specified type and document.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to check.</param>
|
||||
/// <param name="documentName">The OpenAPI document name.</param>
|
||||
/// <returns><c>true</c> if this handler can handle the type; otherwise, <c>false</c>.</returns>
|
||||
bool CanHandle(Type type, string documentName);
|
||||
|
||||
/// <summary>
|
||||
/// Discovers sub-types for the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to discover sub-types for.</param>
|
||||
/// <returns>An enumerable of discovered sub-types.</returns>
|
||||
IEnumerable<Type> Handle(Type type);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a selector for choosing sub-types from registered handlers.
|
||||
/// </summary>
|
||||
public interface ISubTypesSelector
|
||||
{
|
||||
/// <summary>
|
||||
/// Selects sub-types for the specified type for polymorphic OpenAPI schema generation.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to find sub-types for.</param>
|
||||
/// <returns>An enumerable of sub-types.</returns>
|
||||
IEnumerable<Type> SubTypes(Type type);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// This filter explicitly removes all other mime types than application/json from a named OpenAPI document when application/json is accepted.
|
||||
/// </summary>
|
||||
public class MimeTypeDocumentFilter : IDocumentFilter
|
||||
{
|
||||
private readonly string _documentName;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MimeTypeDocumentFilter"/> class.
|
||||
/// </summary>
|
||||
/// <param name="documentName">The name of the OpenAPI document to filter.</param>
|
||||
public MimeTypeDocumentFilter(string documentName) => _documentName = documentName;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
|
||||
{
|
||||
if (context.DocumentName != _documentName)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
OpenApiOperation[] operations = swaggerDoc.Paths
|
||||
.SelectMany(path => path.Value.Operations?.Values ?? Enumerable.Empty<OpenApiOperation>())
|
||||
.ToArray();
|
||||
|
||||
static void RemoveUnwantedMimeTypes(IDictionary<string, OpenApiMediaType>? content)
|
||||
{
|
||||
if (content is null || content.ContainsKey("application/json") is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
content.RemoveAll(r => r.Key != "application/json");
|
||||
}
|
||||
|
||||
OpenApiRequestBody[] requestBodies = operations
|
||||
.Select(operation => operation.RequestBody)
|
||||
.OfType<OpenApiRequestBody>()
|
||||
.ToArray();
|
||||
foreach (OpenApiRequestBody requestBody in requestBodies)
|
||||
{
|
||||
RemoveUnwantedMimeTypes(requestBody.Content);
|
||||
}
|
||||
|
||||
OpenApiResponse[] responses = operations
|
||||
.SelectMany(operation => operation.Responses?.Values ?? Enumerable.Empty<IOpenApiResponse>())
|
||||
.OfType<OpenApiResponse>()
|
||||
.ToArray();
|
||||
foreach (OpenApiResponse response in responses)
|
||||
{
|
||||
RemoveUnwantedMimeTypes(response.Content);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
using System.Net.Mime;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Trims redundant JSON-equivalent media types from OpenAPI operations.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// ASP.NET Core's content negotiation populates operations with several media types that all serialize to JSON
|
||||
/// (<c>text/json</c>, <c>application/*+json</c>, and <c>text/plain</c> alongside <c>application/json</c>).
|
||||
/// When <c>application/json</c> is present on a response or request body, this transformer strips those
|
||||
/// equivalents so OpenAPI consumers and generated SDKs aren't burdened with variants that produce identical
|
||||
/// payloads. Non-JSON media types (e.g. <c>application/xml</c>, <c>application/octet-stream</c>) are preserved.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Request bodies additionally honour <c>[Consumes]</c>: when the attribute is present, the request content is
|
||||
/// replaced entirely with the declared content types, taking precedence over the
|
||||
/// JSON-equivalent stripping above.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal class MimeTypesTransformer : IOpenApiOperationTransformer
|
||||
{
|
||||
private static readonly string[] _jsonEquivalentMimeTypes =
|
||||
[
|
||||
MediaTypeNames.Text.Plain,
|
||||
"application/*+json",
|
||||
"text/json"
|
||||
];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public Task TransformAsync(
|
||||
OpenApiOperation operation,
|
||||
OpenApiOperationTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// For request bodies, keep only the content types declared in [Consumes], or fall back to application/json.
|
||||
if (operation.RequestBody?.Content is { } requestContent)
|
||||
{
|
||||
var explicitContentTypes = context.Description.ActionDescriptor.EndpointMetadata
|
||||
.OfType<ConsumesAttribute>()
|
||||
.SelectMany(p => p.ContentTypes)
|
||||
.Distinct()
|
||||
.ToArray();
|
||||
|
||||
if (explicitContentTypes.Length != 0)
|
||||
{
|
||||
// Replace content types entirely with what [Consumes] declares,
|
||||
// preserving the schema from the existing entry.
|
||||
OpenApiMediaType? existingMediaType = requestContent.Values.FirstOrDefault();
|
||||
requestContent.Clear();
|
||||
foreach (var contentType in explicitContentTypes)
|
||||
{
|
||||
requestContent[contentType] = existingMediaType ?? new OpenApiMediaType();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoveJsonEquivalentMimeTypes(requestContent);
|
||||
}
|
||||
}
|
||||
|
||||
// For responses, drop JSON-equivalent media types when application/json is present.
|
||||
foreach (IOpenApiResponse response in (operation.Responses ?? []).Values)
|
||||
{
|
||||
if (response is OpenApiResponse openApiResponse)
|
||||
{
|
||||
RemoveJsonEquivalentMimeTypes(openApiResponse.Content);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static void RemoveJsonEquivalentMimeTypes(IDictionary<string, OpenApiMediaType>? content)
|
||||
{
|
||||
if (content?.ContainsKey(MediaTypeNames.Application.Json) != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
content.RemoveAll(r => _jsonEquivalentMimeTypes.Contains(r.Key, StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Swashbuckle.AspNetCore.SwaggerUI;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Web.Common.ApplicationBuilder;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
internal class OpenApiRouteTemplatePipelineFilter : UmbracoPipelineFilter
|
||||
{
|
||||
public OpenApiRouteTemplatePipelineFilter(string name)
|
||||
: base(name)
|
||||
{
|
||||
PostPipeline = PostPipelineAction;
|
||||
PreMapEndpoints = OnPreMapEndpointsAction;
|
||||
}
|
||||
|
||||
private static void PostPipelineAction(IApplicationBuilder applicationBuilder)
|
||||
{
|
||||
UmbracoOpenApiOptions options = applicationBuilder.ApplicationServices
|
||||
.GetRequiredService<IOptions<UmbracoOpenApiOptions>>().Value;
|
||||
|
||||
if (options.Enabled is false || options.DefaultUiEnabled is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
applicationBuilder.UseSwaggerUI(swaggerUiOptions => ConfigureSwaggerUi(swaggerUiOptions, options));
|
||||
}
|
||||
|
||||
private static void OnPreMapEndpointsAction(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
UmbracoOpenApiOptions options = endpoints.ServiceProvider
|
||||
.GetRequiredService<IOptions<UmbracoOpenApiOptions>>().Value;
|
||||
|
||||
if (options.Enabled is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
endpoints.MapOpenApi(options.RouteTemplate);
|
||||
}
|
||||
|
||||
private static void ConfigureSwaggerUi(SwaggerUIOptions swaggerUiOptions, UmbracoOpenApiOptions options)
|
||||
{
|
||||
swaggerUiOptions.RoutePrefix = options.UiRoutePrefix;
|
||||
|
||||
// Add custom configuration from https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/
|
||||
swaggerUiOptions.ConfigObject.PersistAuthorization = true; // persists authorization data so it would not be lost on browser close/refresh
|
||||
swaggerUiOptions.ConfigObject.Filter = string.Empty; // Enable the filter with an empty string as default filter.
|
||||
|
||||
swaggerUiOptions.OAuthClientId(Constants.OAuthClientIds.OpenApiUi);
|
||||
swaggerUiOptions.OAuthUsePkce();
|
||||
}
|
||||
}
|
||||
+39
-30
@@ -1,54 +1,63 @@
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Transforms OpenAPI operation IDs using Umbraco's naming conventions.
|
||||
/// Default handler for generating OpenAPI operation IDs for Umbraco API controllers.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This transformer can be registered manually for custom OpenAPI configurations.
|
||||
/// Left unsealed on purpose, so it is extendable by consuming APIs.
|
||||
/// </remarks>
|
||||
public class UmbracoOperationIdTransformer : IOpenApiOperationTransformer
|
||||
public class OperationIdHandler : IOperationIdHandler
|
||||
{
|
||||
private readonly ApiVersioningOptions _apiVersioningOptions;
|
||||
|
||||
/// <summary>
|
||||
/// Transforms the specified OpenAPI operation, setting its operation ID using a custom selector.
|
||||
/// Initializes a new instance of the <see cref="OperationIdHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="operation">The <see cref="OpenApiOperation"/> to modify.</param>
|
||||
/// <param name="context">The <see cref="OpenApiOperationTransformerContext"/> associated with the <paramref name="operation"/>.</param>
|
||||
/// <param name="cancellationToken">The cancellation token to use.</param>
|
||||
/// <returns>The task object representing the asynchronous operation.</returns>
|
||||
public Task TransformAsync(
|
||||
OpenApiOperation operation,
|
||||
OpenApiOperationTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var operationId = GenerateOperationId(context);
|
||||
if (operationId is not null)
|
||||
{
|
||||
operation.OperationId = operationId;
|
||||
}
|
||||
/// <param name="apiVersioningOptions">The API versioning options.</param>
|
||||
public OperationIdHandler(IOptions<ApiVersioningOptions> apiVersioningOptions)
|
||||
=> _apiVersioningOptions = apiVersioningOptions.Value;
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static string? GenerateOperationId(OpenApiOperationTransformerContext context)
|
||||
/// <inheritdoc/>
|
||||
public bool CanHandle(ApiDescription apiDescription)
|
||||
{
|
||||
ApiDescription apiDescription = context.Description;
|
||||
if (apiDescription.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor)
|
||||
{
|
||||
// Minimal APIs and other non-MVC endpoints don't carry a ControllerActionDescriptor; leave their
|
||||
// operation ID untouched so the framework's default applies.
|
||||
return null;
|
||||
return false;
|
||||
}
|
||||
|
||||
ApiVersion defaultVersion = context.ApplicationServices.GetRequiredService<IOptions<ApiVersioningOptions>>().Value.DefaultApiVersion;
|
||||
return CanHandle(apiDescription, controllerActionDescriptor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether this handler can process the API description based on the controller namespace.
|
||||
/// </summary>
|
||||
/// <param name="apiDescription">The API description.</param>
|
||||
/// <param name="controllerActionDescriptor">The controller action descriptor.</param>
|
||||
/// <returns><c>true</c> if the controller is in an Umbraco.Cms.Api namespace; otherwise, <c>false</c>.</returns>
|
||||
protected virtual bool CanHandle(ApiDescription apiDescription, ControllerActionDescriptor controllerActionDescriptor)
|
||||
=> controllerActionDescriptor.ControllerTypeInfo.Namespace?.StartsWith("Umbraco.Cms.Api") is true;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual string Handle(ApiDescription apiDescription)
|
||||
=> UmbracoOperationId(apiDescription);
|
||||
|
||||
/// <summary>
|
||||
/// Generates a unique operation identifier for a given API following Umbraco's operation id naming conventions.
|
||||
/// </summary>
|
||||
protected string UmbracoOperationId(ApiDescription apiDescription)
|
||||
{
|
||||
if (apiDescription.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor)
|
||||
{
|
||||
throw new ArgumentException($"This handler operates only on {nameof(ControllerActionDescriptor)}.");
|
||||
}
|
||||
|
||||
ApiVersion defaultVersion = _apiVersioningOptions.DefaultApiVersion;
|
||||
var httpMethod = apiDescription.HttpMethod?.ToLower().ToFirstUpper() ?? "Get";
|
||||
|
||||
// if the route info "Name" is supplied we'll use this explicitly as the operation ID
|
||||
@@ -0,0 +1,35 @@
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Selects an operation ID for an API description using registered handlers.
|
||||
/// </summary>
|
||||
public class OperationIdSelector : IOperationIdSelector
|
||||
{
|
||||
private readonly IEnumerable<IOperationIdHandler> _operationIdHandlers;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OperationIdSelector"/> class.
|
||||
/// </summary>
|
||||
[Obsolete("Use non-obsolete constructor. Scheduled for removal in Umbraco 18.")]
|
||||
public OperationIdSelector()
|
||||
: this(Enumerable.Empty<IOperationIdHandler>())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OperationIdSelector"/> class.
|
||||
/// </summary>
|
||||
/// <param name="operationIdHandlers">The registered operation ID handlers.</param>
|
||||
public OperationIdSelector(IEnumerable<IOperationIdHandler> operationIdHandlers)
|
||||
=> _operationIdHandlers = operationIdHandlers;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual string? OperationId(ApiDescription apiDescription)
|
||||
{
|
||||
IOperationIdHandler? handler = _operationIdHandlers.FirstOrDefault(h => h.CanHandle(apiDescription));
|
||||
return handler?.Handle(apiDescription);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// This filter explicitly removes all security schemes from a named OpenAPI document.
|
||||
/// </summary>
|
||||
public class RemoveSecuritySchemesDocumentFilter : IDocumentFilter
|
||||
{
|
||||
private readonly string _documentName;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveSecuritySchemesDocumentFilter"/> class.
|
||||
/// </summary>
|
||||
/// <param name="documentName">The name of the OpenAPI document to filter.</param>
|
||||
public RemoveSecuritySchemesDocumentFilter(string documentName)
|
||||
=> _documentName = documentName;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
|
||||
{
|
||||
if (context.DocumentName != _documentName)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
swaggerDoc.Components?.SecuritySchemes?.Clear();
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Ensures that all non-nullable properties are marked as required in the OpenAPI schema.
|
||||
/// </summary>
|
||||
/// <remarks>By default, only properties marked with the required keyword will actually show as required.
|
||||
/// Non-nullable reference types were not taken into account.</remarks>
|
||||
internal class RequireNonNullablePropertiesSchemaTransformer : IOpenApiSchemaTransformer
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
IEnumerable<string> additionalRequiredProps = schema.Properties?
|
||||
.Where(p => schema.Required?.Contains(p.Key) != true) // If it's already required, skip
|
||||
.Where(x => IsRequiredProperty(schema, context.JsonTypeInfo, x.Key))
|
||||
.Select(x => x.Key)
|
||||
?? [];
|
||||
schema.Required ??= new HashSet<string>();
|
||||
foreach (var propKey in additionalRequiredProps)
|
||||
{
|
||||
schema.Required.Add(propKey);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static bool IsRequiredProperty(OpenApiSchema schema, JsonTypeInfo jsonTypeInfo, string propertyName)
|
||||
{
|
||||
if (jsonTypeInfo.Properties.FirstOrDefault(p => p.Name == propertyName) is { } property)
|
||||
{
|
||||
return property.IsGetNullable is false;
|
||||
}
|
||||
|
||||
// If we can't find the property in the type (e.g. discriminator '$type'), use the schema type information.
|
||||
if (schema.Properties?.TryGetValue(propertyName, out IOpenApiSchema? schemaProperty) is true
|
||||
&& schemaProperty?.Type is { } propertyType)
|
||||
{
|
||||
return propertyType.HasFlag(JsonSchemaType.Null) is false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Default handler for generating OpenAPI schema IDs for Umbraco types.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Left unsealed on purpose, so it is extendable by consuming APIs.
|
||||
/// Adds "Model" suffix to avoid TypeScript name clashes and removes invalid characters.
|
||||
/// </remarks>
|
||||
public class SchemaIdHandler : ISchemaIdHandler
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public virtual bool CanHandle(Type type)
|
||||
=> type.Namespace?.StartsWith("Umbraco.Cms") is true;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual string Handle(Type type)
|
||||
=> UmbracoSchemaId(type);
|
||||
|
||||
/// <summary>
|
||||
/// Generates a sanitized and consistent schema identifier for a given type following Umbraco's schema id naming conventions.
|
||||
/// </summary>
|
||||
protected string UmbracoSchemaId(Type type)
|
||||
{
|
||||
var name = SanitizedTypeName(type);
|
||||
|
||||
name = HandleGenerics(name, type);
|
||||
|
||||
if (name.EndsWith("Model") == false)
|
||||
{
|
||||
// because some models names clash with common classes in TypeScript (i.e. Document),
|
||||
// we need to add a "Model" postfix to all models
|
||||
name = $"{name}Model";
|
||||
}
|
||||
|
||||
// make absolutely sure we don't pass any invalid named by removing all non-word chars
|
||||
return Regex.Replace(name, @"[^\w]", string.Empty);
|
||||
}
|
||||
|
||||
private string SanitizedTypeName(Type t) => t.Name
|
||||
// first grab the "non-generic" part of any generic type name (i.e. "PagedViewModel`1" becomes "PagedViewModel")
|
||||
.Split('`').First()
|
||||
// then remove the "ViewModel" postfix from type names
|
||||
.TrimEnd("ViewModel");
|
||||
|
||||
private string HandleGenerics(string name, Type type)
|
||||
{
|
||||
if (!type.IsGenericType)
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
// use attribute custom name or append the generic type names, ultimately turning i.e. "PagedViewModel<RelationItemViewModel>" into "PagedRelationItem"
|
||||
return $"{name}{string.Join(string.Empty, type.GenericTypeArguments.Select(SanitizedTypeName))}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Selects a schema ID for a type using registered handlers.
|
||||
/// </summary>
|
||||
public class SchemaIdSelector : ISchemaIdSelector
|
||||
{
|
||||
private readonly IEnumerable<ISchemaIdHandler> _schemaIdHandlers;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SchemaIdSelector"/> class.
|
||||
/// </summary>
|
||||
/// <param name="schemaIdHandlers">The registered schema ID handlers.</param>
|
||||
public SchemaIdSelector(IEnumerable<ISchemaIdHandler> schemaIdHandlers)
|
||||
=> _schemaIdHandlers = schemaIdHandlers;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual string SchemaId(Type type)
|
||||
{
|
||||
ISchemaIdHandler? handler = _schemaIdHandlers.FirstOrDefault(h => h.CanHandle(type));
|
||||
return handler?.Handle(type) ?? type.Name;
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Transforms the OpenAPI document to sort tags and paths alphabetically.
|
||||
/// </summary>
|
||||
internal class SortTagsAndPathsTransformer : IOpenApiDocumentTransformer
|
||||
{
|
||||
/// <summary>
|
||||
/// Transforms the specified OpenAPI document to sort its tags and paths alphabetically.
|
||||
/// </summary>
|
||||
/// <param name="document">The <see cref="OpenApiDocument"/> to modify.</param>
|
||||
/// <param name="context">The <see cref="OpenApiDocumentTransformerContext"/> associated with the <paramref name="document"/>.</param>
|
||||
/// <param name="cancellationToken">The cancellation token to use.</param>
|
||||
/// <returns>The task object representing the asynchronous operation.</returns>
|
||||
public Task TransformAsync(
|
||||
OpenApiDocument document,
|
||||
OpenApiDocumentTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
document.Tags = new SortedSet<OpenApiTag>(
|
||||
document.Tags ?? Enumerable.Empty<OpenApiTag>(),
|
||||
Comparer<OpenApiTag>.Create((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal)));
|
||||
|
||||
var sortedPaths = new OpenApiPaths();
|
||||
foreach (KeyValuePair<string, IOpenApiPathItem> keyValuePair in document.Paths
|
||||
.OrderBy(x => x.Value.Operations?.Values
|
||||
.SelectMany(op => op.Tags ?? Enumerable.Empty<OpenApiTagReference>())
|
||||
.OrderBy(t => t.Name)
|
||||
.FirstOrDefault()?
|
||||
.Name)
|
||||
.ThenBy(x => x.Key))
|
||||
{
|
||||
sortedPaths.Add(keyValuePair.Key, keyValuePair.Value);
|
||||
}
|
||||
|
||||
document.Paths = sortedPaths;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Umbraco.Cms.Api.Common.Serialization;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Default handler for discovering sub-types for polymorphic OpenAPI schemas.
|
||||
/// </summary>
|
||||
public class SubTypesHandler : ISubTypesHandler
|
||||
{
|
||||
private readonly IUmbracoJsonTypeInfoResolver _umbracoJsonTypeInfoResolver;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SubTypesHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="umbracoJsonTypeInfoResolver">The JSON type info resolver for finding sub-types.</param>
|
||||
public SubTypesHandler(IUmbracoJsonTypeInfoResolver umbracoJsonTypeInfoResolver)
|
||||
=> _umbracoJsonTypeInfoResolver = umbracoJsonTypeInfoResolver;
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether this handler can process the specified type based on namespace.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to check.</param>
|
||||
/// <returns><c>true</c> if the type is in an Umbraco.Cms namespace; otherwise, <c>false</c>.</returns>
|
||||
protected virtual bool CanHandle(Type type)
|
||||
=> type.Namespace?.StartsWith("Umbraco.Cms") is true;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual bool CanHandle(Type type, string documentName)
|
||||
=> CanHandle(type);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual IEnumerable<Type> Handle(Type type)
|
||||
=> _umbracoJsonTypeInfoResolver.FindSubTypes(type);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Umbraco.Cms.Api.Common.Serialization;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Configuration.Models;
|
||||
using Umbraco.Cms.Core.Hosting;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Selects sub-types for polymorphic OpenAPI schemas using registered handlers.
|
||||
/// </summary>
|
||||
public class SubTypesSelector : ISubTypesSelector
|
||||
{
|
||||
private readonly IHostingEnvironment _hostingEnvironment;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly IEnumerable<ISubTypesHandler> _subTypeHandlers;
|
||||
private readonly IUmbracoJsonTypeInfoResolver _umbracoJsonTypeInfoResolver;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SubTypesSelector"/> class.
|
||||
/// </summary>
|
||||
/// <param name="hostingEnvironment">The hosting environment.</param>
|
||||
/// <param name="httpContextAccessor">The HTTP context accessor.</param>
|
||||
/// <param name="subTypeHandlers">The registered sub-type handlers.</param>
|
||||
/// <param name="umbracoJsonTypeInfoResolver">The JSON type info resolver for finding sub-types.</param>
|
||||
public SubTypesSelector(
|
||||
IHostingEnvironment hostingEnvironment,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IEnumerable<ISubTypesHandler> subTypeHandlers,
|
||||
IUmbracoJsonTypeInfoResolver umbracoJsonTypeInfoResolver)
|
||||
{
|
||||
_hostingEnvironment = hostingEnvironment;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_subTypeHandlers = subTypeHandlers;
|
||||
_umbracoJsonTypeInfoResolver = umbracoJsonTypeInfoResolver;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IEnumerable<Type> SubTypes(Type type)
|
||||
{
|
||||
var backOfficePath = _hostingEnvironment.GetBackOfficePath();
|
||||
var swaggerPath = $"{backOfficePath}/swagger";
|
||||
|
||||
if (_httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(swaggerPath) ?? false)
|
||||
{
|
||||
// Split the path into segments
|
||||
var segments = _httpContextAccessor.HttpContext.Request.Path.Value![swaggerPath.Length..]
|
||||
.TrimStart(Constants.CharArrays.ForwardSlash)
|
||||
.Split(Constants.CharArrays.ForwardSlash);
|
||||
|
||||
// Extract the document name from the path
|
||||
var documentName = segments[0];
|
||||
|
||||
// Find the first handler that can handle the type / document name combination
|
||||
ISubTypesHandler? handler = _subTypeHandlers.FirstOrDefault(h => h.CanHandle(type, documentName));
|
||||
if (handler != null)
|
||||
{
|
||||
return handler.Handle(type);
|
||||
}
|
||||
}
|
||||
|
||||
// Default implementation to maintain backwards compatibility
|
||||
return _umbracoJsonTypeInfoResolver.FindSubTypes(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Swashbuckle.AspNetCore.SwaggerUI;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Hosting;
|
||||
using Umbraco.Cms.Web.Common.ApplicationBuilder;
|
||||
using IHostingEnvironment = Umbraco.Cms.Core.Hosting.IHostingEnvironment;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Pipeline filter that configures Swagger/OpenAPI endpoints for Umbraco APIs.
|
||||
/// </summary>
|
||||
public class SwaggerRouteTemplatePipelineFilter : UmbracoPipelineFilter
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SwaggerRouteTemplatePipelineFilter"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the pipeline filter.</param>
|
||||
public SwaggerRouteTemplatePipelineFilter(string name)
|
||||
: base(name)
|
||||
=> PostPipeline = PostPipelineAction;
|
||||
|
||||
private void PostPipelineAction(IApplicationBuilder applicationBuilder)
|
||||
{
|
||||
if (SwaggerIsEnabled(applicationBuilder) is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IOptions<SwaggerGenOptions> swaggerGenOptions = applicationBuilder.ApplicationServices.GetRequiredService<IOptions<SwaggerGenOptions>>();
|
||||
|
||||
applicationBuilder.UseSwagger(swaggerOptions =>
|
||||
{
|
||||
swaggerOptions.RouteTemplate = SwaggerRouteTemplate(applicationBuilder);
|
||||
});
|
||||
|
||||
applicationBuilder.UseSwaggerUI(swaggerUiOptions => SwaggerUiConfiguration(swaggerUiOptions, swaggerGenOptions.Value, applicationBuilder));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether Swagger is enabled for the application.
|
||||
/// </summary>
|
||||
/// <param name="applicationBuilder">The application builder.</param>
|
||||
/// <returns><c>true</c> if Swagger is enabled; otherwise, <c>false</c>.</returns>
|
||||
protected virtual bool SwaggerIsEnabled(IApplicationBuilder applicationBuilder)
|
||||
=> applicationBuilder.ApplicationServices.GetRequiredService<IWebHostEnvironment>().IsProduction() is false;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the route template for Swagger JSON endpoints.
|
||||
/// </summary>
|
||||
/// <param name="applicationBuilder">The application builder.</param>
|
||||
/// <returns>The Swagger route template.</returns>
|
||||
protected virtual string SwaggerRouteTemplate(IApplicationBuilder applicationBuilder)
|
||||
=> $"{GetBackOfficePath(applicationBuilder).TrimStart(Constants.CharArrays.ForwardSlash)}/swagger/{{documentName}}/swagger.json";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the route prefix for the Swagger UI.
|
||||
/// </summary>
|
||||
/// <param name="applicationBuilder">The application builder.</param>
|
||||
/// <returns>The Swagger UI route prefix.</returns>
|
||||
protected virtual string SwaggerUiRoutePrefix(IApplicationBuilder applicationBuilder)
|
||||
=> $"{GetBackOfficePath(applicationBuilder).TrimStart(Constants.CharArrays.ForwardSlash)}/swagger";
|
||||
|
||||
/// <summary>
|
||||
/// Configures the Swagger UI options.
|
||||
/// </summary>
|
||||
/// <param name="swaggerUiOptions">The Swagger UI options to configure.</param>
|
||||
/// <param name="swaggerGenOptions">The Swagger generation options.</param>
|
||||
/// <param name="applicationBuilder">The application builder.</param>
|
||||
protected virtual void SwaggerUiConfiguration(
|
||||
SwaggerUIOptions swaggerUiOptions,
|
||||
SwaggerGenOptions swaggerGenOptions,
|
||||
IApplicationBuilder applicationBuilder)
|
||||
{
|
||||
swaggerUiOptions.RoutePrefix = SwaggerUiRoutePrefix(applicationBuilder);
|
||||
|
||||
foreach ((var name, OpenApiInfo? apiInfo) in swaggerGenOptions.SwaggerGeneratorOptions.SwaggerDocs.OrderBy(x => x.Value.Title))
|
||||
{
|
||||
swaggerUiOptions.SwaggerEndpoint($"{name}/swagger.json", $"{apiInfo.Title}");
|
||||
}
|
||||
|
||||
// Add custom configuration from https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/
|
||||
swaggerUiOptions.ConfigObject.PersistAuthorization = true; // persists authorization data so it would not be lost on browser close/refresh
|
||||
swaggerUiOptions.ConfigObject.Filter = string.Empty; // Enable the filter with an empty string as default filter.
|
||||
|
||||
swaggerUiOptions.OAuthClientId(Constants.OAuthClientIds.Swagger);
|
||||
swaggerUiOptions.OAuthUsePkce();
|
||||
}
|
||||
|
||||
private string GetBackOfficePath(IApplicationBuilder applicationBuilder)
|
||||
=> applicationBuilder.ApplicationServices.GetRequiredService<IHostingEnvironment>().GetBackOfficePath();
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Transformer that tags operations based on their group name.
|
||||
/// </summary>
|
||||
internal class TagActionsByGroupNameTransformer : IOpenApiOperationTransformer, IOpenApiDocumentTransformer
|
||||
{
|
||||
/// <summary>
|
||||
/// Transforms the specified OpenAPI operation in order to tag it by its group name.
|
||||
/// </summary>
|
||||
/// <param name="operation">The <see cref="OpenApiOperation"/> to modify.</param>
|
||||
/// <param name="context">The <see cref="OpenApiOperationTransformerContext"/> associated with the <paramref name="operation"/>.</param>
|
||||
/// <param name="cancellationToken">The cancellation token to use.</param>
|
||||
/// <returns>The task object representing the asynchronous operation.</returns>
|
||||
public Task TransformAsync(
|
||||
OpenApiOperation operation,
|
||||
OpenApiOperationTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (context.Document is null || context.Description.GroupName is not { } groupName)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
operation.Tags = new HashSet<OpenApiTagReference> { new(groupName) };
|
||||
if (context.Document.Tags?.Any(t => t.Name == groupName) == true)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
context.Document.Tags ??= new HashSet<OpenApiTag>();
|
||||
context.Document.Tags.Add(new OpenApiTag { Name = groupName });
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Transforms the specified OpenAPI document in order to clean up unused tags.
|
||||
/// </summary>
|
||||
/// <param name="document">The <see cref="OpenApiDocument"/> to modify.</param>
|
||||
/// <param name="context">The <see cref="OpenApiDocumentTransformerContext"/> associated with the <paramref name="document"/>.</param>
|
||||
/// <param name="cancellationToken">The cancellation token to use.</param>
|
||||
/// <returns>The task object representing the asynchronous operation.</returns>
|
||||
public Task TransformAsync(
|
||||
OpenApiDocument document,
|
||||
OpenApiDocumentTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var usedTags = new HashSet<string?>(document.Paths
|
||||
.SelectMany(p => (p.Value.Operations ?? []).Values)
|
||||
.SelectMany(o => o.Tags ?? new HashSet<OpenApiTagReference>())
|
||||
.Select(t => t.Name));
|
||||
|
||||
var tagsToRemove = (document.Tags ?? Enumerable.Empty<OpenApiTag>())
|
||||
.Where(tag => usedTags.Contains(tag.Name) is false)
|
||||
.ToList();
|
||||
|
||||
foreach (OpenApiTag tag in tagsToRemove)
|
||||
{
|
||||
document.Tags?.Remove(tag);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
using Umbraco.Cms.Core.DependencyInjection;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for <see cref="IUmbracoBuilder"/> to register custom OpenAPI documents.
|
||||
/// </summary>
|
||||
public static class UmbracoBuilderOpenApiExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers a custom OpenAPI document with Umbraco's defaults applied.
|
||||
/// </summary>
|
||||
/// <param name="builder">The Umbraco builder.</param>
|
||||
/// <param name="documentName">The document name. Matches the <c>[MapToApi]</c> value on controllers to include.</param>
|
||||
/// <param name="configure">Optional callback to customize the document.</param>
|
||||
/// <returns>The same <see cref="IUmbracoBuilder"/> for chaining.</returns>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The following defaults are applied to the document and can be customized or overridden via the
|
||||
/// <paramref name="configure"/> callback:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// Endpoints are filtered by <c>[MapToApi(documentName)]</c>; only matching endpoints appear in the document.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// Schema reference IDs are generated by <see cref="UmbracoSchemaIdGenerator.CreateSchemaReferenceId"/>, applying
|
||||
/// Umbraco naming conventions to types under the <c>Umbraco.Cms</c> namespace and falling back to the framework
|
||||
/// default for everything else. Register your own <c>CreateSchemaReferenceId</c> delegate via
|
||||
/// <see cref="BackOfficeOpenApiDocumentBuilder.ConfigureOpenApiOptions"/> to override.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// Operation IDs are generated by <see cref="UmbracoOperationIdTransformer"/>. Register your own
|
||||
/// <see cref="Microsoft.AspNetCore.OpenApi.IOpenApiOperationTransformer"/> via
|
||||
/// <see cref="BackOfficeOpenApiDocumentBuilder.ConfigureOpenApiOptions"/> to override.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// Operations are tagged by their controller's API group name, and the resulting tags and paths are sorted
|
||||
/// for stable, diffable document output.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// Redundant JSON-equivalent media types (such as <c>text/json</c>, <c>application/*+json</c>, and
|
||||
/// <c>text/plain</c>) are stripped from request and response content when <c>application/json</c> is present,
|
||||
/// so the document doesn't list spurious media types that ASP.NET Core adds by default.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// Non-nullable properties are marked as <c>required</c> in the schema so generated client SDKs reflect
|
||||
/// C# nullability. Override via <see cref="BackOfficeOpenApiDocumentBuilder.ConfigureOpenApiOptions"/>
|
||||
/// if your types don't follow this convention.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// The document is registered in the OpenAPI UI document selector dropdown. Call
|
||||
/// <see cref="BackOfficeOpenApiDocumentBuilder.ExcludeFromUi"/> to opt out.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public static IUmbracoBuilder AddBackOfficeOpenApiDocument(
|
||||
this IUmbracoBuilder builder,
|
||||
string documentName,
|
||||
Action<BackOfficeOpenApiDocumentBuilder>? configure = null)
|
||||
{
|
||||
var documentBuilder = new BackOfficeOpenApiDocumentBuilder(documentName);
|
||||
configure?.Invoke(documentBuilder);
|
||||
documentBuilder.Build(builder);
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Options for configuring OpenAPI documents and UI.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// These options are populated by <c>AddUmbracoOpenApi</c> during DI configuration, which resolves the back-office path
|
||||
/// from <see cref="Core.Hosting.IHostingEnvironment"/> and sets the default values for
|
||||
/// <see cref="RouteTemplate"/> and <see cref="UiRoutePrefix"/>. Consumers that read this options type before
|
||||
/// <c>AddUmbracoOpenApi</c> has run will observe the uninitialised defaults (empty strings for the route properties).
|
||||
/// </remarks>
|
||||
public class UmbracoOpenApiOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets whether OpenAPI documents are enabled.
|
||||
/// Configured to <c>true</c> in non-production environments by default; <c>false</c> until configured.
|
||||
/// This avoids exposing API structure on public-facing websites.
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the default OpenAPI UI is enabled.
|
||||
/// Only applies when <see cref="Enabled"/> is true.
|
||||
/// Set to false to disable the default UI while keeping OpenAPI documents available,
|
||||
/// allowing you to use an alternative UI.
|
||||
/// Default: true.
|
||||
/// </summary>
|
||||
public bool DefaultUiEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the route template for OpenAPI JSON documents.
|
||||
/// Use <c>{documentName}</c> as a placeholder for the document name.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Populated by <c>AddUmbracoOpenApi</c> to <c>"{backOfficePath}/openapi/{documentName}.json"</c>. The initial
|
||||
/// <see cref="string.Empty"/> default is a sentinel for "not yet configured" — it is not a usable route template.
|
||||
/// </remarks>
|
||||
public string RouteTemplate { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the route prefix for OpenAPI UI.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Populated by <c>AddUmbracoOpenApi</c> to <c>"{backOfficePath}/openapi"</c>. The initial <see cref="string.Empty"/>
|
||||
/// default is a sentinel for "not yet configured" — it is not a usable route prefix.
|
||||
/// </remarks>
|
||||
public string UiRoutePrefix { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Common.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Static utility for generating OpenAPI schema IDs following Umbraco's naming conventions.
|
||||
/// </summary>
|
||||
public static class UmbracoSchemaIdGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a schema ID for the specified type following Umbraco's naming conventions.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to generate a schema ID for.</param>
|
||||
/// <returns>The generated schema ID.</returns>
|
||||
public static string Generate(Type type)
|
||||
{
|
||||
var name = SanitizedTypeName(type);
|
||||
name = HandleGenerics(name, type);
|
||||
|
||||
if (name.EndsWith("Model") == false)
|
||||
{
|
||||
// because some models names clash with common classes in TypeScript (i.e. Document),
|
||||
// we need to add a "Model" postfix to all models
|
||||
name = $"{name}Model";
|
||||
}
|
||||
|
||||
// make absolutely sure we don't pass any invalid named by removing all non-word chars
|
||||
return Regex.Replace(name, @"[^\w]", string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a schema reference ID for the given JSON type info, applying Umbraco's naming conventions to
|
||||
/// types in the <c>Umbraco.Cms</c> namespace and falling back to the framework default for other types.
|
||||
/// </summary>
|
||||
/// <param name="jsonTypeInfo">The JSON type info to create a schema reference ID for.</param>
|
||||
/// <returns>The schema reference ID, or <c>null</c> if the type should be inlined.</returns>
|
||||
internal static string? CreateSchemaReferenceId(JsonTypeInfo jsonTypeInfo)
|
||||
{
|
||||
// Ensure that only types that would normally be included in the schema generation are given a schema reference ID.
|
||||
// Otherwise, we should return null to inline them.
|
||||
var defaultSchemaReferenceId = OpenApiOptions.CreateDefaultSchemaReferenceId(jsonTypeInfo);
|
||||
if (defaultSchemaReferenceId is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Type targetType = Nullable.GetUnderlyingType(jsonTypeInfo.Type) ?? jsonTypeInfo.Type;
|
||||
|
||||
if (targetType.Namespace?.StartsWith("Umbraco.Cms") is not true)
|
||||
{
|
||||
return defaultSchemaReferenceId;
|
||||
}
|
||||
|
||||
return Generate(targetType);
|
||||
}
|
||||
|
||||
private static string SanitizedTypeName(Type t) => t.Name
|
||||
// first grab the "non-generic" part of any generic type name (i.e. "PagedViewModel`1" becomes "PagedViewModel")
|
||||
.Split('`').First()
|
||||
// then remove the "ViewModel" postfix from type names
|
||||
.TrimEnd("ViewModel");
|
||||
|
||||
private static string HandleGenerics(string name, Type type)
|
||||
{
|
||||
if (!type.IsGenericType)
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
// use attribute custom name or append the generic type names, ultimately turning i.e. "PagedViewModel<RelationItemViewModel>" into "PagedRelationItem"
|
||||
return $"{name}{string.Join(string.Empty, type.GenericTypeArguments.Select(SanitizedTypeName))}";
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using OpenIddict.Server;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Configuration.Models;
|
||||
using Umbraco.Cms.Core.Security;
|
||||
using Umbraco.Extensions;
|
||||
@@ -33,12 +32,12 @@ public class ExposeBackOfficeAuthenticationOpenIddictServerEventsHandler : IOpen
|
||||
|
||||
// These are the type identifiers for the claims required by the principal
|
||||
// for the custom authentication scheme.
|
||||
// We make available the ID and user name claims, plus the claim necessary for parsing the user key.
|
||||
// We make available the ID, user name and allowed applications (sections) claims.
|
||||
_claimTypes =
|
||||
[
|
||||
backOfficeIdentityOptions.Value.ClaimsIdentity.UserIdClaimType,
|
||||
backOfficeIdentityOptions.Value.ClaimsIdentity.UserNameClaimType,
|
||||
Constants.Security.OpenIdDictSubClaimType
|
||||
Core.Constants.Security.AllowedApplicationsClaimType,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,6 @@
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>Umbraco.Tests.UnitTests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>Umbraco.Cms.Api.Management</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>Umbraco.Cms.Api.Delivery</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -21,12 +15,11 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Asp.Versioning.Mvc" />
|
||||
<PackageReference Include="Asp.Versioning.Mvc "/>
|
||||
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" />
|
||||
<PackageReference Include="OpenIddict.Abstractions" />
|
||||
<PackageReference Include="OpenIddict.AspNetCore" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -39,7 +39,7 @@ Umbraco.Cms.Api.Delivery/
|
||||
├── Services/ # Business logic and query building
|
||||
├── Caching/ # Output cache policies
|
||||
├── Rendering/ # Output expansion strategies
|
||||
├── Configuration/ # OpenAPI configuration
|
||||
├── Configuration/ # Swagger configuration
|
||||
└── Filters/ # Action filters (access, validation)
|
||||
```
|
||||
|
||||
@@ -200,9 +200,10 @@ context.EnableOutputCaching = requestPreviewService.IsPreview() is false
|
||||
|
||||
### Technical Debt (TODOs in codebase)
|
||||
|
||||
1. **V1 Removal Pending** (2 locations):
|
||||
1. **V1 Removal Pending** (4 locations):
|
||||
- `DependencyInjection/UmbracoBuilderExtensions.cs:98` - FIXME: remove matcher policy
|
||||
- `Routing/DeliveryApiItemsEndpointsMatcherPolicy.cs:11` - FIXME: remove class
|
||||
- `Filters/SwaggerDocumentationFilterBase.cs:79,83` - FIXME: remove V1 swagger docs
|
||||
|
||||
2. **Obsolete Reference Warnings** (csproj:9-13):
|
||||
- `ASP0019` - IHeaderDictionary.Append usage
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Umbraco.Cms.Core.DeliveryApi;
|
||||
using Umbraco.Cms.Core.Models.PublishedContent;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation of <see cref="IDeliveryApiOutputCacheRequestFilter"/> that prevents caching
|
||||
/// for preview mode requests and requests without public access.
|
||||
/// </summary>
|
||||
public class DefaultDeliveryApiOutputCacheRequestFilter : IDeliveryApiOutputCacheRequestFilter
|
||||
{
|
||||
private readonly IRequestPreviewService _requestPreviewService;
|
||||
private readonly IApiAccessService _apiAccessService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DefaultDeliveryApiOutputCacheRequestFilter"/> class.
|
||||
/// </summary>
|
||||
/// <param name="requestPreviewService">The preview service.</param>
|
||||
/// <param name="apiAccessService">The API access service.</param>
|
||||
public DefaultDeliveryApiOutputCacheRequestFilter(IRequestPreviewService requestPreviewService, IApiAccessService apiAccessService)
|
||||
{
|
||||
_requestPreviewService = requestPreviewService;
|
||||
_apiAccessService = apiAccessService;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public virtual bool IsCacheable(HttpContext context)
|
||||
=> IsPreview() is false && HasPublicAccess();
|
||||
|
||||
/// <inheritdoc />
|
||||
public virtual bool IsCacheable(HttpContext context, IPublishedContent content) => true;
|
||||
|
||||
/// <summary>
|
||||
/// Returns <c>true</c> if the current request is a preview request; <c>false</c> if the request
|
||||
/// is not a preview and may be cached.
|
||||
/// </summary>
|
||||
protected virtual bool IsPreview()
|
||||
=> _requestPreviewService.IsPreview();
|
||||
|
||||
/// <summary>
|
||||
/// Returns <c>true</c> if the current request has public access; <c>false</c> if the request
|
||||
/// is not publicly accessible and should not be cached.
|
||||
/// </summary>
|
||||
protected virtual bool HasPublicAccess()
|
||||
=> _apiAccessService.HasPublicAccess();
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
using Umbraco.Cms.Core.Models.PublishedContent;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Tags cached pages for delivery API output caching with their content type alias, enabling eviction by content type.
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiContentTypeOutputCacheTagProvider : IDeliveryApiOutputCacheTagProvider
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<string> GetTags(IPublishedContent content)
|
||||
{
|
||||
yield return Constants.DeliveryApi.OutputCache.ContentTypeTagPrefix + content.ContentType.Alias;
|
||||
}
|
||||
}
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
using Umbraco.Cms.Core.Events;
|
||||
using Umbraco.Cms.Core.Notifications;
|
||||
using Umbraco.Cms.Core.Services;
|
||||
using Umbraco.Cms.Core.Services.Changes;
|
||||
using Umbraco.Cms.Core.Sync;
|
||||
using Umbraco.Cms.Web.Common.Caching;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="ContentCacheRefresherNotification"/> to evict Delivery API output cache entries
|
||||
/// when content is published, unpublished, moved, or deleted. Also evicts responses for content
|
||||
/// that references the changed content via picker properties (umbDocument relations).
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiDocumentOutputCacheEvictionHandler
|
||||
: RelationOutputCacheEvictionHandlerBase, INotificationAsyncHandler<ContentCacheRefresherNotification>
|
||||
{
|
||||
private readonly IEnumerable<IDeliveryApiOutputCacheEvictionProvider> _evictionProviders;
|
||||
private readonly ILogger<DeliveryApiDocumentOutputCacheEvictionHandler> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiDocumentOutputCacheEvictionHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="outputCacheStore">The output cache store for evicting cached responses.</param>
|
||||
/// <param name="relationService">The relation service for querying entity references.</param>
|
||||
/// <param name="idKeyMap">The ID/key mapping service for converting between integer IDs and GUIDs.</param>
|
||||
/// <param name="evictionProviders">Custom eviction providers for additional tag-based eviction.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public DeliveryApiDocumentOutputCacheEvictionHandler(
|
||||
IOutputCacheStore outputCacheStore,
|
||||
IRelationService relationService,
|
||||
IIdKeyMap idKeyMap,
|
||||
IEnumerable<IDeliveryApiOutputCacheEvictionProvider> evictionProviders,
|
||||
ILogger<DeliveryApiDocumentOutputCacheEvictionHandler> logger)
|
||||
: base(outputCacheStore, relationService, idKeyMap)
|
||||
{
|
||||
_evictionProviders = evictionProviders;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task HandleAsync(ContentCacheRefresherNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
if (notification.MessageType != MessageType.RefreshByPayload
|
||||
|| notification.MessageObject is not ContentCacheRefresher.JsonPayload[] payloads)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var changedEntityIds = new List<int>();
|
||||
|
||||
foreach (ContentCacheRefresher.JsonPayload payload in payloads)
|
||||
{
|
||||
if (payload.Blueprint)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await EvictForPayloadAsync(payload, cancellationToken);
|
||||
changedEntityIds.Add(payload.Id);
|
||||
}
|
||||
|
||||
// Evict content that references the changed content via picker properties.
|
||||
await EvictRelatedContentAsync(
|
||||
changedEntityIds,
|
||||
Constants.Conventions.RelationTypes.RelatedDocumentAlias,
|
||||
Constants.DeliveryApi.OutputCache.ContentTagPrefix,
|
||||
_logger,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private async Task EvictForPayloadAsync(ContentCacheRefresher.JsonPayload payload, CancellationToken cancellationToken)
|
||||
{
|
||||
if (payload.ChangeTypes.HasFlag(TreeChangeTypes.RefreshAll))
|
||||
{
|
||||
// Evict all Delivery API responses — media responses may reference content via picker properties.
|
||||
_logger.LogDebug("Content refresh all — evicting all Delivery API output cache entries.");
|
||||
await OutputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.AllTag, cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.Key.HasValue is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Guid contentKey = payload.Key.Value;
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug("Evicting Delivery API output cache for content {ContentKey}.", contentKey);
|
||||
}
|
||||
|
||||
await OutputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.ContentTagPrefix + contentKey, cancellationToken);
|
||||
|
||||
if (payload.ChangeTypes.HasFlag(TreeChangeTypes.RefreshBranch))
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug("Evicting Delivery API output cache for descendants of {ContentKey}.", contentKey);
|
||||
}
|
||||
|
||||
await OutputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.AncestorTagPrefix + contentKey, cancellationToken);
|
||||
}
|
||||
|
||||
await InvokeCustomEvictionProvidersAsync(payload, contentKey, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task InvokeCustomEvictionProvidersAsync(ContentCacheRefresher.JsonPayload payload, Guid contentKey, CancellationToken cancellationToken)
|
||||
{
|
||||
var context = new OutputCacheContentChangedContext(
|
||||
payload.Id,
|
||||
contentKey,
|
||||
payload.PublishedCultures ?? [],
|
||||
payload.UnpublishedCultures ?? []);
|
||||
|
||||
foreach (IDeliveryApiOutputCacheEvictionProvider provider in _evictionProviders)
|
||||
{
|
||||
IEnumerable<string> additionalTags = await provider.GetAdditionalEvictionTagsAsync(context, cancellationToken);
|
||||
foreach (var tag in additionalTags)
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug("Evicting Delivery API output cache tag {Tag} via custom provider.", tag);
|
||||
}
|
||||
|
||||
await OutputCacheStore.EvictByTagAsync(tag, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
using Umbraco.Cms.Core.Events;
|
||||
using Umbraco.Cms.Core.Notifications;
|
||||
using Umbraco.Cms.Core.Services;
|
||||
using Umbraco.Cms.Core.Services.Changes;
|
||||
using Umbraco.Cms.Core.Sync;
|
||||
using Umbraco.Cms.Web.Common.Caching;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="ElementCacheRefresherNotification"/> to evict Delivery API output cache entries
|
||||
/// for content that references the changed element via picker properties (umbElement relations).
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiElementOutputCacheEvictionHandler
|
||||
: RelationOutputCacheEvictionHandlerBase, INotificationAsyncHandler<ElementCacheRefresherNotification>
|
||||
{
|
||||
private readonly ILogger<DeliveryApiElementOutputCacheEvictionHandler> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiElementOutputCacheEvictionHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="outputCacheStore">The output cache store for evicting cached responses.</param>
|
||||
/// <param name="relationService">The relation service for querying entity references.</param>
|
||||
/// <param name="idKeyMap">The ID/key mapping service for converting between integer IDs and GUIDs.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public DeliveryApiElementOutputCacheEvictionHandler(
|
||||
IOutputCacheStore outputCacheStore,
|
||||
IRelationService relationService,
|
||||
IIdKeyMap idKeyMap,
|
||||
ILogger<DeliveryApiElementOutputCacheEvictionHandler> logger)
|
||||
: base(outputCacheStore, relationService, idKeyMap)
|
||||
=> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task HandleAsync(ElementCacheRefresherNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
if (notification.MessageType != MessageType.RefreshByPayload
|
||||
|| notification.MessageObject is not ElementCacheRefresher.JsonPayload[] payloads)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (ElementCacheRefresher.JsonPayload payload in payloads)
|
||||
{
|
||||
if (payload.ChangeTypes.HasFlag(TreeChangeTypes.RefreshAll))
|
||||
{
|
||||
// Evict all Delivery API responses — content responses may include referenced elements,
|
||||
// so evicting only element-related entries would leave stale element references in content responses.
|
||||
_logger.LogDebug("Element refresh all — evicting all Delivery API output cache entries.");
|
||||
await OutputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.AllTag, cancellationToken);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Evict content that references the changed elements via picker properties.
|
||||
await EvictRelatedContentAsync(
|
||||
payloads.Select(p => p.Id),
|
||||
Constants.Conventions.RelationTypes.RelatedElementAlias,
|
||||
Constants.DeliveryApi.OutputCache.ContentTagPrefix,
|
||||
_logger,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
using Umbraco.Cms.Core.Events;
|
||||
using Umbraco.Cms.Core.Notifications;
|
||||
using Umbraco.Cms.Core.Services;
|
||||
using Umbraco.Cms.Core.Services.Changes;
|
||||
using Umbraco.Cms.Core.Sync;
|
||||
using Umbraco.Cms.Web.Common.Caching;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="MediaCacheRefresherNotification"/> to evict Delivery API output cache entries
|
||||
/// when media is created, updated, or deleted. Also evicts content responses that reference
|
||||
/// the changed media via picker properties (umbMedia relations).
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiMediaOutputCacheEvictionHandler
|
||||
: RelationOutputCacheEvictionHandlerBase, INotificationAsyncHandler<MediaCacheRefresherNotification>
|
||||
{
|
||||
private readonly ILogger<DeliveryApiMediaOutputCacheEvictionHandler> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiMediaOutputCacheEvictionHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="outputCacheStore">The output cache store for evicting cached responses.</param>
|
||||
/// <param name="relationService">The relation service for querying entity references.</param>
|
||||
/// <param name="idKeyMap">The ID/key mapping service for converting between integer IDs and GUIDs.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public DeliveryApiMediaOutputCacheEvictionHandler(
|
||||
IOutputCacheStore outputCacheStore,
|
||||
IRelationService relationService,
|
||||
IIdKeyMap idKeyMap,
|
||||
ILogger<DeliveryApiMediaOutputCacheEvictionHandler> logger)
|
||||
: base(outputCacheStore, relationService, idKeyMap)
|
||||
=> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task HandleAsync(MediaCacheRefresherNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
if (notification.MessageType != MessageType.RefreshByPayload
|
||||
|| notification.MessageObject is not MediaCacheRefresher.JsonPayload[] payloads)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (MediaCacheRefresher.JsonPayload payload in payloads)
|
||||
{
|
||||
if (payload.ChangeTypes.HasFlag(TreeChangeTypes.RefreshAll))
|
||||
{
|
||||
// Evict all Delivery API responses — content responses may include referenced media,
|
||||
// so evicting only media entries would leave stale media references in content responses.
|
||||
_logger.LogDebug("Media refresh all — evicting all Delivery API output cache entries.");
|
||||
await OutputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.AllTag, cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.Key.HasValue is false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug("Evicting Delivery API output cache for media {MediaKey}.", payload.Key.Value);
|
||||
}
|
||||
|
||||
await OutputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.MediaTagPrefix + payload.Key.Value, cancellationToken);
|
||||
}
|
||||
|
||||
// Evict content that references the changed media via picker properties.
|
||||
await EvictRelatedContentAsync(
|
||||
payloads.Select(p => p.Id),
|
||||
Constants.Conventions.RelationTypes.RelatedMediaAlias,
|
||||
Constants.DeliveryApi.OutputCache.ContentTagPrefix,
|
||||
_logger,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
using Umbraco.Cms.Core.Events;
|
||||
using Umbraco.Cms.Core.Notifications;
|
||||
using Umbraco.Cms.Core.Services;
|
||||
using Umbraco.Cms.Core.Sync;
|
||||
using Umbraco.Cms.Web.Common.Caching;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Handles <see cref="MemberCacheRefresherNotification"/> to evict Delivery API output cache entries
|
||||
/// for content that references the changed member via picker properties (umbMember relations).
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiMemberOutputCacheEvictionHandler
|
||||
: RelationOutputCacheEvictionHandlerBase, INotificationAsyncHandler<MemberCacheRefresherNotification>
|
||||
{
|
||||
private readonly ILogger<DeliveryApiMemberOutputCacheEvictionHandler> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiMemberOutputCacheEvictionHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="outputCacheStore">The output cache store for evicting cached responses.</param>
|
||||
/// <param name="relationService">The relation service for querying entity references.</param>
|
||||
/// <param name="idKeyMap">The ID/key mapping service for converting between integer IDs and GUIDs.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public DeliveryApiMemberOutputCacheEvictionHandler(
|
||||
IOutputCacheStore outputCacheStore,
|
||||
IRelationService relationService,
|
||||
IIdKeyMap idKeyMap,
|
||||
ILogger<DeliveryApiMemberOutputCacheEvictionHandler> logger)
|
||||
: base(outputCacheStore, relationService, idKeyMap)
|
||||
=> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task HandleAsync(MemberCacheRefresherNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
if (notification.MessageType != MessageType.RefreshByPayload
|
||||
|| notification.MessageObject is not MemberCacheRefresher.JsonPayload[] payloads)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Evict content that references the changed members via picker properties.
|
||||
await EvictRelatedContentAsync(
|
||||
payloads.Select(p => p.Id),
|
||||
Constants.Conventions.RelationTypes.RelatedMemberAlias,
|
||||
Constants.DeliveryApi.OutputCache.ContentTagPrefix,
|
||||
_logger,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Models.PublishedContent;
|
||||
using Umbraco.Cms.Core.Services.Navigation;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Output cache policy for Delivery API content endpoints.
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiOutputCacheContentPolicy : DeliveryApiOutputCachePolicyBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiOutputCacheContentPolicy"/> class.
|
||||
/// </summary>
|
||||
/// <param name="defaultDuration">The default cache duration from configuration.</param>
|
||||
/// <param name="defaultVaryByHeaders">The default vary-by headers for content requests.</param>
|
||||
public DeliveryApiOutputCacheContentPolicy(TimeSpan defaultDuration, StringValues defaultVaryByHeaders)
|
||||
: base(defaultDuration, defaultVaryByHeaders)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ResolvedItemsKey => DeliveryApiOutputCacheKeys.ResolvedContentItemsKey;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ItemTagPrefix => Constants.DeliveryApi.OutputCache.ContentTagPrefix;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string AllItemsTag => Constants.DeliveryApi.OutputCache.AllContentTag;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void AddItemTags(OutputCacheContext context, IPublishedContent item, IServiceProvider services)
|
||||
{
|
||||
// Tag with ancestor keys for branch eviction.
|
||||
IDocumentNavigationQueryService navigationService = services.GetRequiredService<IDocumentNavigationQueryService>();
|
||||
if (navigationService.TryGetAncestorsKeys(item.Key, out IEnumerable<Guid> ancestorKeys))
|
||||
{
|
||||
foreach (Guid ancestorKey in ancestorKeys)
|
||||
{
|
||||
context.Tags.Add(Constants.DeliveryApi.OutputCache.AncestorTagPrefix + ancestorKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Keys used to pass resolved content and media items from controllers to the output cache policy
|
||||
/// via <see cref="Microsoft.AspNetCore.Http.HttpContext.Items"/>.
|
||||
/// </summary>
|
||||
internal static class DeliveryApiOutputCacheKeys
|
||||
{
|
||||
/// <summary>
|
||||
/// Key for storing resolved content items in <see cref="Microsoft.AspNetCore.Http.HttpContext.Items"/>.
|
||||
/// </summary>
|
||||
public const string ResolvedContentItemsKey = "Umbraco.DeliveryApi.OutputCache.ResolvedContentItems";
|
||||
|
||||
/// <summary>
|
||||
/// Key for storing resolved media items in <see cref="Microsoft.AspNetCore.Http.HttpContext.Items"/>.
|
||||
/// </summary>
|
||||
public const string ResolvedMediaItemsKey = "Umbraco.DeliveryApi.OutputCache.ResolvedMediaItems";
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation of <see cref="IDeliveryApiOutputCacheManager"/> that delegates
|
||||
/// to the ASP.NET Core <see cref="IOutputCacheStore"/>.
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiOutputCacheManager : IDeliveryApiOutputCacheManager
|
||||
{
|
||||
private readonly IOutputCacheStore _outputCacheStore;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiOutputCacheManager"/> class.
|
||||
/// </summary>
|
||||
/// <param name="outputCacheStore">The ASP.NET Core output cache store.</param>
|
||||
public DeliveryApiOutputCacheManager(IOutputCacheStore outputCacheStore)
|
||||
=> _outputCacheStore = outputCacheStore;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EvictContentAsync(Guid contentKey, CancellationToken cancellationToken = default)
|
||||
=> await _outputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.ContentTagPrefix + contentKey, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EvictMediaAsync(Guid mediaKey, CancellationToken cancellationToken = default)
|
||||
=> await _outputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.MediaTagPrefix + mediaKey, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EvictByTagAsync(string tag, CancellationToken cancellationToken = default)
|
||||
=> await _outputCacheStore.EvictByTagAsync(tag, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EvictAllContentAsync(CancellationToken cancellationToken = default)
|
||||
=> await _outputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.AllContentTag, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EvictAllMediaAsync(CancellationToken cancellationToken = default)
|
||||
=> await _outputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.AllMediaTag, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EvictAllAsync(CancellationToken cancellationToken = default)
|
||||
=> await _outputCacheStore.EvictByTagAsync(Constants.DeliveryApi.OutputCache.AllTag, cancellationToken);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Umbraco.Cms.Core;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Output cache policy for Delivery API media endpoints.
|
||||
/// </summary>
|
||||
internal sealed class DeliveryApiOutputCacheMediaPolicy : DeliveryApiOutputCachePolicyBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiOutputCacheMediaPolicy"/> class.
|
||||
/// </summary>
|
||||
/// <param name="defaultDuration">The default cache duration from configuration.</param>
|
||||
/// <param name="defaultVaryByHeaders">The default vary-by headers for media requests.</param>
|
||||
public DeliveryApiOutputCacheMediaPolicy(TimeSpan defaultDuration, StringValues defaultVaryByHeaders)
|
||||
: base(defaultDuration, defaultVaryByHeaders)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ResolvedItemsKey => DeliveryApiOutputCacheKeys.ResolvedMediaItemsKey;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ItemTagPrefix => Constants.DeliveryApi.OutputCache.MediaTagPrefix;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string AllItemsTag => Constants.DeliveryApi.OutputCache.AllMediaTag;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Umbraco.Cms.Core.DeliveryApi;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
internal sealed class DeliveryApiOutputCachePolicy : IOutputCachePolicy
|
||||
{
|
||||
private readonly TimeSpan _duration;
|
||||
private readonly StringValues _varyByHeaderNames;
|
||||
|
||||
public DeliveryApiOutputCachePolicy(TimeSpan duration, StringValues varyByHeaderNames)
|
||||
{
|
||||
_duration = duration;
|
||||
_varyByHeaderNames = varyByHeaderNames;
|
||||
}
|
||||
|
||||
ValueTask IOutputCachePolicy.CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
IRequestPreviewService requestPreviewService = context
|
||||
.HttpContext
|
||||
.RequestServices
|
||||
.GetRequiredService<IRequestPreviewService>();
|
||||
|
||||
IApiAccessService apiAccessService = context
|
||||
.HttpContext
|
||||
.RequestServices
|
||||
.GetRequiredService<IApiAccessService>();
|
||||
|
||||
context.EnableOutputCaching = requestPreviewService.IsPreview() is false && apiAccessService.HasPublicAccess();
|
||||
context.ResponseExpirationTimeSpan = _duration;
|
||||
context.CacheVaryByRules.HeaderNames = _varyByHeaderNames;
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
ValueTask IOutputCachePolicy.ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
ValueTask IOutputCachePolicy.ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken)
|
||||
=> ValueTask.CompletedTask;
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
using Umbraco.Cms.Core.Models.PublishedContent;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Base output cache policy for Delivery API endpoints. Handles request filtering, vary-by rules,
|
||||
/// and tagging. Subclasses specify the resolved-items key, tag prefix, and "all" tag that
|
||||
/// distinguish content from media.
|
||||
/// </summary>
|
||||
internal abstract class DeliveryApiOutputCachePolicyBase : IOutputCachePolicy
|
||||
{
|
||||
private readonly TimeSpan _defaultDuration;
|
||||
private readonly StringValues _defaultVaryByHeaders;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeliveryApiOutputCachePolicyBase"/> class.
|
||||
/// </summary>
|
||||
/// <param name="defaultDuration">The default cache duration from configuration.</param>
|
||||
/// <param name="defaultVaryByHeaders">The default vary-by headers for this endpoint type.</param>
|
||||
protected DeliveryApiOutputCachePolicyBase(TimeSpan defaultDuration, StringValues defaultVaryByHeaders)
|
||||
{
|
||||
_defaultDuration = defaultDuration;
|
||||
_defaultVaryByHeaders = defaultVaryByHeaders;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="Microsoft.AspNetCore.Http.HttpContext.Items"/> key used to retrieve
|
||||
/// resolved <see cref="IPublishedContent"/> items stashed by the controller.
|
||||
/// </summary>
|
||||
protected abstract string ResolvedItemsKey { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag prefix for individual item eviction (e.g. <c>umb-dapi-content-</c>).
|
||||
/// </summary>
|
||||
protected abstract string ItemTagPrefix { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the "all items" tag for bulk eviction (e.g. <c>umb-dapi-content-all</c>).
|
||||
/// </summary>
|
||||
protected abstract string AllItemsTag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Adds additional per-item tags to the output cache context. Called once per resolved item
|
||||
/// during <c>ServeResponseAsync</c>. The default implementation does nothing.
|
||||
/// </summary>
|
||||
/// <param name="context">The output cache context.</param>
|
||||
/// <param name="item">The published content or media item.</param>
|
||||
/// <param name="services">The request service provider.</param>
|
||||
protected virtual void AddItemTags(OutputCacheContext context, IPublishedContent item, IServiceProvider services)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
ValueTask IOutputCachePolicy.CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
IServiceProvider services = context.HttpContext.RequestServices;
|
||||
ILogger logger = services.GetRequiredService<ILoggerFactory>().CreateLogger(GetType());
|
||||
|
||||
IDeliveryApiOutputCacheRequestFilter requestFilter = services.GetRequiredService<IDeliveryApiOutputCacheRequestFilter>();
|
||||
if (requestFilter.IsCacheable(context.HttpContext) is false)
|
||||
{
|
||||
context.EnableOutputCaching = false;
|
||||
logger.LogDebug("Request filter returned not cacheable — skipping output cache.");
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
context.EnableOutputCaching = true;
|
||||
context.AllowCacheLookup = true;
|
||||
context.AllowCacheStorage = true;
|
||||
context.AllowLocking = true;
|
||||
context.ResponseExpirationTimeSpan = _defaultDuration;
|
||||
|
||||
// Set default vary-by headers.
|
||||
context.CacheVaryByRules.HeaderNames = _defaultVaryByHeaders;
|
||||
|
||||
// Invoke custom vary-by providers (additive, runs after defaults).
|
||||
IEnumerable<IDeliveryApiOutputCacheVaryByProvider> varyByProviders = services.GetServices<IDeliveryApiOutputCacheVaryByProvider>();
|
||||
foreach (IDeliveryApiOutputCacheVaryByProvider varyByProvider in varyByProviders)
|
||||
{
|
||||
varyByProvider.ConfigureVaryBy(context.HttpContext, context.CacheVaryByRules);
|
||||
}
|
||||
|
||||
// Add base tags for bulk eviction.
|
||||
context.Tags.Add(AllItemsTag);
|
||||
context.Tags.Add(Constants.DeliveryApi.OutputCache.AllTag);
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
ValueTask IOutputCachePolicy.ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
/// <inheritdoc />
|
||||
ValueTask IOutputCachePolicy.ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (context.HttpContext.Items[ResolvedItemsKey]
|
||||
is not IPublishedContent[] items || items.Length == 0)
|
||||
{
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
IServiceProvider services = context.HttpContext.RequestServices;
|
||||
ILogger logger = services.GetRequiredService<ILoggerFactory>().CreateLogger(GetType());
|
||||
IDeliveryApiOutputCacheRequestFilter requestFilter = services.GetRequiredService<IDeliveryApiOutputCacheRequestFilter>();
|
||||
IEnumerable<IDeliveryApiOutputCacheTagProvider> tagProviders = services.GetServices<IDeliveryApiOutputCacheTagProvider>();
|
||||
|
||||
foreach (IPublishedContent item in items)
|
||||
{
|
||||
// Check content-aware cacheability.
|
||||
if (requestFilter.IsCacheable(context.HttpContext, item) is false)
|
||||
{
|
||||
context.AllowCacheStorage = false;
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Request filter returned not cacheable for item {ItemKey} — disabling cache storage.", item.Key);
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
// Tag with specific item key for targeted eviction.
|
||||
context.Tags.Add(ItemTagPrefix + item.Key);
|
||||
|
||||
// Allow subclasses to add additional per-item tags (e.g. ancestor tags for content).
|
||||
AddItemTags(context, item, services);
|
||||
|
||||
// Invoke custom tag providers.
|
||||
foreach (IDeliveryApiOutputCacheTagProvider tagProvider in tagProviders)
|
||||
{
|
||||
foreach (var tag in tagProvider.GetTags(item))
|
||||
{
|
||||
context.Tags.Add(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Caching Delivery API response with {TagCount} tags, duration {Duration}",
|
||||
context.Tags.Count,
|
||||
context.ResponseExpirationTimeSpan);
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Umbraco.Cms.Core.Models.PublishedContent;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a Delivery API request is eligible for output caching.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This interface provides two levels of cacheability checks:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item><see cref="IsCacheable(HttpContext)"/> — called before the controller runs, for
|
||||
/// request-level decisions (e.g. preview mode, access control).</item>
|
||||
/// <item><see cref="IsCacheable(HttpContext, IPublishedContent)"/> — called after the controller
|
||||
/// resolves content, for content-aware decisions (e.g. exclude specific content types).</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public interface IDeliveryApiOutputCacheRequestFilter
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the request is eligible for output caching.
|
||||
/// Called before the controller runs.
|
||||
/// </summary>
|
||||
/// <param name="context">The HTTP context for the current request.</param>
|
||||
/// <returns><c>true</c> if the response may be cached; <c>false</c> to skip caching.</returns>
|
||||
bool IsCacheable(HttpContext context);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the response for the given content or media item is eligible
|
||||
/// for output caching. Called after the controller resolves content.
|
||||
/// </summary>
|
||||
/// <param name="context">The HTTP context for the current request.</param>
|
||||
/// <param name="content">The resolved published content or media item.</param>
|
||||
/// <returns><c>true</c> if the response may be cached; <c>false</c> to skip caching.</returns>
|
||||
bool IsCacheable(HttpContext context, IPublishedContent content);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
/// <summary>
|
||||
/// Configures additional vary-by rules for Delivery API output caching.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Multiple implementations can be registered; the output cache policy invokes all of them
|
||||
/// to configure vary-by rules at cache-write time, after the default vary-by headers have been set.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Providers have direct access to <see cref="CacheVaryByRules"/> and can configure any aspect
|
||||
/// including <see cref="CacheVaryByRules.QueryKeys"/>, <see cref="CacheVaryByRules.HeaderNames"/>,
|
||||
/// and <see cref="CacheVaryByRules.VaryByValues"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public interface IDeliveryApiOutputCacheVaryByProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures vary-by rules for the given request.
|
||||
/// </summary>
|
||||
/// <param name="context">The HTTP context for the current request.</param>
|
||||
/// <param name="rules">The vary-by rules to configure.</param>
|
||||
void ConfigureVaryBy(HttpContext context, CacheVaryByRules rules);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Umbraco.Cms.Web.Common.ApplicationBuilder;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Caching;
|
||||
|
||||
internal sealed class OutputCachePipelineFilter : UmbracoPipelineFilter
|
||||
{
|
||||
public OutputCachePipelineFilter(string name)
|
||||
: base(name)
|
||||
=> PostPipeline = PostPipelineAction;
|
||||
|
||||
private void PostPipelineAction(IApplicationBuilder applicationBuilder)
|
||||
=> applicationBuilder.UseOutputCache();
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Umbraco.Cms.Api.Common.Configuration;
|
||||
using Umbraco.Cms.Api.Common.OpenApi;
|
||||
using Umbraco.Cms.Api.Delivery.OpenApi.Transformers;
|
||||
using Umbraco.Cms.Core.Configuration.Models;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the OpenAPI options for the Umbraco Delivery API.
|
||||
/// </summary>
|
||||
internal class ConfigureUmbracoDeliveryApiOpenApiOptions : ConfigureUmbracoOpenApiOptionsBase
|
||||
{
|
||||
private readonly DeliveryApiSettings _deliveryApiSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConfigureUmbracoDeliveryApiOpenApiOptions"/> class.
|
||||
/// </summary>
|
||||
/// <param name="deliveryApiSettings">The Delivery API settings.</param>
|
||||
public ConfigureUmbracoDeliveryApiOpenApiOptions(IOptions<DeliveryApiSettings> deliveryApiSettings)
|
||||
{
|
||||
_deliveryApiSettings = deliveryApiSettings.Value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ApiName => DeliveryApiConfiguration.ApiName;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ApiTitle => DeliveryApiConfiguration.ApiTitle;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ApiVersion => "Latest";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ApiDescription =>
|
||||
$"You can find out more about the {DeliveryApiConfiguration.ApiTitle} in [the documentation]({DeliveryApiConfiguration.ApiDocumentationContentArticleLink}).";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void ConfigureOpenApi(OpenApiOptions options)
|
||||
{
|
||||
base.ConfigureOpenApi(options);
|
||||
|
||||
// Add API key security scheme and configure it for all operations
|
||||
options
|
||||
.AddDocumentTransformer<ApiKeyTransformer>()
|
||||
.AddOperationTransformer<ApiKeyTransformer>();
|
||||
|
||||
options.AddSchemaTransformer<RequireNonNullablePropertiesSchemaTransformer>();
|
||||
options.AddSchemaTransformer<FixFileReturnTypesTransformer>();
|
||||
options.AddOperationTransformer<MimeTypesTransformer>();
|
||||
options.AddOperationTransformer<ContentApiTransformer>();
|
||||
options.AddOperationTransformer<MediaApiTransformer>();
|
||||
|
||||
if (_deliveryApiSettings.OpenApi.GenerateContentTypeSchemas)
|
||||
{
|
||||
options
|
||||
.AddSchemaTransformer<ContentTypeSchemaTransformer>()
|
||||
.AddDocumentTransformer<ContentTypeSchemaTransformer>();
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Cms.Api.Common.OpenApi;
|
||||
using Umbraco.Cms.Api.Delivery.Filters;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Configuration;
|
||||
|
||||
public class ConfigureUmbracoDeliveryApiSwaggerGenOptions: IConfigureOptions<SwaggerGenOptions>
|
||||
{
|
||||
public void Configure(SwaggerGenOptions swaggerGenOptions)
|
||||
{
|
||||
swaggerGenOptions.SwaggerDoc(
|
||||
DeliveryApiConfiguration.ApiName,
|
||||
new OpenApiInfo
|
||||
{
|
||||
Title = DeliveryApiConfiguration.ApiTitle,
|
||||
Version = "Latest",
|
||||
Description = $"You can find out more about the {DeliveryApiConfiguration.ApiTitle} in [the documentation]({DeliveryApiConfiguration.ApiDocumentationContentArticleLink})."
|
||||
});
|
||||
|
||||
swaggerGenOptions.DocumentFilter<MimeTypeDocumentFilter>(DeliveryApiConfiguration.ApiName);
|
||||
swaggerGenOptions.DocumentFilter<RemoveSecuritySchemesDocumentFilter>(DeliveryApiConfiguration.ApiName);
|
||||
|
||||
swaggerGenOptions.OperationFilter<SwaggerContentDocumentationFilter>();
|
||||
swaggerGenOptions.OperationFilter<SwaggerMediaDocumentationFilter>();
|
||||
swaggerGenOptions.ParameterFilter<SwaggerContentDocumentationFilter>();
|
||||
swaggerGenOptions.ParameterFilter<SwaggerMediaDocumentationFilter>();
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Http.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Umbraco.Cms.Core;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the Http JSON options for the Umbraco Delivery API.
|
||||
/// </summary>
|
||||
internal class ConfigureUmbracoDeliveryHttpJsonOptions : IConfigureNamedOptions<JsonOptions>
|
||||
{
|
||||
private readonly IOptionsMonitor<Microsoft.AspNetCore.Mvc.JsonOptions> _mvcJsonOptions;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConfigureUmbracoDeliveryHttpJsonOptions"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mvcJsonOptions">The configured MVC json options.</param>
|
||||
public ConfigureUmbracoDeliveryHttpJsonOptions(IOptionsMonitor<Microsoft.AspNetCore.Mvc.JsonOptions> mvcJsonOptions)
|
||||
=> _mvcJsonOptions = mvcJsonOptions;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Configure(JsonOptions options) => Configure(Options.DefaultName, options);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Configure(string? name, JsonOptions options)
|
||||
{
|
||||
if (name != Constants.JsonOptionsNames.DeliveryApi)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Copy all converters from the Delivery API MVC JSON options
|
||||
Microsoft.AspNetCore.Mvc.JsonOptions backofficeMvcJsonOptions = _mvcJsonOptions.Get(Constants.JsonOptionsNames.DeliveryApi);
|
||||
foreach (JsonConverter jsonConverter in backofficeMvcJsonOptions.JsonSerializerOptions.Converters)
|
||||
{
|
||||
options.SerializerOptions.Converters.Add(jsonConverter);
|
||||
}
|
||||
|
||||
options.SerializerOptions.PropertyNamingPolicy = backofficeMvcJsonOptions.JsonSerializerOptions.PropertyNamingPolicy;
|
||||
options.SerializerOptions.TypeInfoResolver = backofficeMvcJsonOptions.JsonSerializerOptions.TypeInfoResolver;
|
||||
options.SerializerOptions.MaxDepth = backofficeMvcJsonOptions.JsonSerializerOptions.MaxDepth;
|
||||
|
||||
// Open API specific settings
|
||||
options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict;
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Cms.Api.Common.Security;
|
||||
using Umbraco.Cms.Api.Delivery.Controllers.Content;
|
||||
using Umbraco.Cms.Api.Delivery.Filters;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// This configures member authentication for the Delivery API in Swagger. Consult the docs for
|
||||
/// member authentication within the Delivery API for instructions on how to use this.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This class is not used by the core CMS due to the required installation dependencies (local login page among other things).
|
||||
/// </remarks>
|
||||
public class ConfigureUmbracoMemberAuthenticationDeliveryApiSwaggerGenOptions : IConfigureOptions<SwaggerGenOptions>
|
||||
{
|
||||
private const string AuthSchemeName = "UmbracoMember";
|
||||
|
||||
public void Configure(SwaggerGenOptions options)
|
||||
{
|
||||
// add security requirements for content API operations
|
||||
options.DocumentFilter<DeliveryApiSecurityFilter>();
|
||||
options.OperationFilter<DeliveryApiSecurityFilter>();
|
||||
}
|
||||
|
||||
private sealed class DeliveryApiSecurityFilter : SwaggerFilterBase<ContentApiControllerBase>, IOperationFilter, IDocumentFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
if (CanApply(context) is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var schemaRef = new OpenApiSecuritySchemeReference(AuthSchemeName, context.Document);
|
||||
operation.Security ??= new List<OpenApiSecurityRequirement>();
|
||||
operation.Security.Add(new OpenApiSecurityRequirement { [schemaRef] = [] });
|
||||
}
|
||||
|
||||
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
|
||||
{
|
||||
if (context.DocumentName != DeliveryApiConfiguration.ApiName)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
swaggerDoc.AddComponent(
|
||||
AuthSchemeName,
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
In = ParameterLocation.Header,
|
||||
Name = AuthSchemeName,
|
||||
Type = SecuritySchemeType.OAuth2,
|
||||
Description = "Umbraco Member Authentication",
|
||||
Flows = new OpenApiOAuthFlows
|
||||
{
|
||||
AuthorizationCode = new OpenApiOAuthFlow
|
||||
{
|
||||
AuthorizationUrl = new Uri(Paths.MemberApi.AuthorizationEndpoint, UriKind.Relative),
|
||||
TokenUrl = new Uri(Paths.MemberApi.TokenEndpoint, UriKind.Relative),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,20 +41,17 @@ public class ByIdContentApiController : ContentApiItemControllerBase
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
IActionResult? deniedAccessResult = await HandleMemberAccessAsync(contentItem, _requestMemberAccessService).ConfigureAwait(false);
|
||||
if (deniedAccessResult is not null)
|
||||
{
|
||||
return deniedAccessResult;
|
||||
}
|
||||
|
||||
IApiContentResponse? apiContentResponse = ApiContentResponseBuilder.Build(contentItem);
|
||||
if (apiContentResponse is null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
SetOutputCacheContent(contentItem);
|
||||
return Ok(apiContentResponse);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,6 @@ public class ByIdsContentApiController : ContentApiItemControllerBase
|
||||
.WhereNotNull()
|
||||
.ToArray();
|
||||
|
||||
SetOutputCacheContent(contentItems);
|
||||
return Ok(apiContentItems);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,6 @@ public class ByRouteContentApiController : ContentApiItemControllerBase
|
||||
return deniedAccessResult;
|
||||
}
|
||||
|
||||
SetOutputCacheContent(contentItem);
|
||||
return Ok(ApiContentResponseBuilder.Build(contentItem));
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,10 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Umbraco.Cms.Api.Common.Builders;
|
||||
using Umbraco.Cms.Api.Delivery.Caching;
|
||||
using Umbraco.Cms.Api.Delivery.Filters;
|
||||
using Umbraco.Cms.Api.Delivery.Routing;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.DeliveryApi;
|
||||
using Umbraco.Cms.Core.Models.PublishedContent;
|
||||
using Umbraco.Cms.Core.Services.OperationStatus;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Controllers.Content;
|
||||
@@ -52,13 +50,6 @@ public abstract class ContentApiControllerBase : DeliveryApiControllerBase
|
||||
.Build()),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Stores the resolved content items in the HTTP context for use by the output cache policy.
|
||||
/// </summary>
|
||||
/// <param name="items">The resolved published content items.</param>
|
||||
protected void SetOutputCacheContent(params IPublishedContent[] items)
|
||||
=> HttpContext.Items[DeliveryApiOutputCacheKeys.ResolvedContentItemsKey] = items;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a 403 Forbidden result.
|
||||
/// </summary>
|
||||
|
||||
@@ -62,11 +62,9 @@ public class QueryContentApiController : ContentApiControllerBase
|
||||
}
|
||||
|
||||
PagedModel<Guid> pagedResult = queryAttempt.Result;
|
||||
IPublishedContent[] contentItems = ApiPublishedContentCache.GetByIds(pagedResult.Items).ToArray();
|
||||
IEnumerable<IPublishedContent> contentItems = ApiPublishedContentCache.GetByIds(pagedResult.Items);
|
||||
IApiContentResponse[] apiContentItems = contentItems.Select(ApiContentResponseBuilder.Build).WhereNotNull().ToArray();
|
||||
|
||||
SetOutputCacheContent(contentItems);
|
||||
|
||||
var model = new PagedViewModel<IApiContentResponse>
|
||||
{
|
||||
Total = pagedResult.Total,
|
||||
|
||||
@@ -20,7 +20,7 @@ public abstract class DeliveryApiControllerBase : Controller, IUmbracoFeature
|
||||
{
|
||||
protected string DecodePath(string path)
|
||||
{
|
||||
// OpenAPI does not allow reserved chars as "in:path" parameters, so clients based on the OpenAPI specification will URL
|
||||
// OpenAPI does not allow reserved chars as "in:path" parameters, so clients based on the Swagger JSON will URL
|
||||
// encode the path. Normally, ASP.NET Core handles that encoding with an automatic decoding - apparently just not
|
||||
// for forward slashes, for whatever reason... so we need to deal with those. Hopefully this will be addressed in
|
||||
// an upcoming version of ASP.NET Core.
|
||||
|
||||
@@ -39,7 +39,6 @@ public class ByIdMediaApiController : MediaApiControllerBase
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
SetOutputCacheMedia(media);
|
||||
return Ok(BuildApiMediaWithCrops(media));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,6 @@ public class ByIdsMediaApiController : MediaApiControllerBase
|
||||
.Select(BuildApiMediaWithCrops)
|
||||
.ToArray();
|
||||
|
||||
SetOutputCacheMedia(mediaItems);
|
||||
return Ok(apiMediaItems);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,6 @@ public class ByPathMediaApiController : MediaApiControllerBase
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
SetOutputCacheMedia(media);
|
||||
return Ok(BuildApiMediaWithCrops(media));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.OutputCaching;
|
||||
using Umbraco.Cms.Api.Common.Builders;
|
||||
using Umbraco.Cms.Api.Delivery.Caching;
|
||||
using Umbraco.Cms.Api.Delivery.Filters;
|
||||
using Umbraco.Cms.Api.Delivery.Routing;
|
||||
using Umbraco.Cms.Core;
|
||||
@@ -34,13 +33,6 @@ public abstract class MediaApiControllerBase : DeliveryApiControllerBase
|
||||
protected IApiMediaWithCropsResponse BuildApiMediaWithCrops(IPublishedContent media)
|
||||
=> _apiMediaWithCropsResponseBuilder.Build(media);
|
||||
|
||||
/// <summary>
|
||||
/// Stores the resolved media items in the HTTP context for use by the output cache policy.
|
||||
/// </summary>
|
||||
/// <param name="items">The resolved published media items.</param>
|
||||
protected void SetOutputCacheMedia(params IPublishedContent[] items)
|
||||
=> HttpContext.Items[DeliveryApiOutputCacheKeys.ResolvedMediaItemsKey] = items;
|
||||
|
||||
protected IActionResult ApiMediaQueryOperationStatusResult(ApiMediaQueryOperationStatus status) =>
|
||||
status switch
|
||||
{
|
||||
|
||||
@@ -59,8 +59,6 @@ public class QueryMediaApiController : MediaApiControllerBase
|
||||
PagedModel<Guid> pagedResult = queryAttempt.Result;
|
||||
IPublishedContent[] mediaItems = pagedResult.Items.Select(PublishedMediaCache.GetById).WhereNotNull().ToArray();
|
||||
|
||||
SetOutputCacheMedia(mediaItems);
|
||||
|
||||
var model = new PagedViewModel<IApiMediaWithCropsResponse>
|
||||
{
|
||||
Total = pagedResult.Total,
|
||||
|
||||
@@ -5,8 +5,6 @@ using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Umbraco.Cms.Api.Common.DependencyInjection;
|
||||
using Umbraco.Cms.Api.Delivery.Accessors;
|
||||
@@ -20,7 +18,6 @@ using Umbraco.Cms.Api.Delivery.Security;
|
||||
using Umbraco.Cms.Api.Delivery.Services;
|
||||
using Umbraco.Cms.Api.Delivery.Services.QueryBuilders;
|
||||
using Umbraco.Cms.Core;
|
||||
using Umbraco.Cms.Core.Cache;
|
||||
using Umbraco.Cms.Core.Configuration.Models;
|
||||
using Umbraco.Cms.Core.DeliveryApi;
|
||||
using Umbraco.Cms.Core.DependencyInjection;
|
||||
@@ -54,7 +51,7 @@ public static class UmbracoBuilderExtensions
|
||||
provider =>
|
||||
{
|
||||
HttpContext? httpContext = provider.GetRequiredService<IHttpContextAccessor>().HttpContext;
|
||||
ApiVersion? apiVersion = httpContext?.RequestedApiVersion;
|
||||
ApiVersion? apiVersion = httpContext?.GetRequestedApiVersion();
|
||||
if (apiVersion is null)
|
||||
{
|
||||
return provider.GetRequiredService<RequestContextOutputExpansionStrategyV2>();
|
||||
@@ -68,6 +65,7 @@ public static class UmbracoBuilderExtensions
|
||||
ServiceLifetime.Scoped);
|
||||
|
||||
builder.Services.AddSingleton<IRequestCultureService, RequestCultureService>();
|
||||
builder.Services.AddSingleton<IRequestSegmmentService, RequestSegmentService>();
|
||||
builder.Services.AddSingleton<IRequestSegmentService, RequestSegmentService>();
|
||||
builder.Services.AddSingleton<IRequestRoutingService, RequestRoutingService>();
|
||||
builder.Services.AddSingleton<IRequestRedirectService, RequestRedirectService>();
|
||||
@@ -86,27 +84,19 @@ public static class UmbracoBuilderExtensions
|
||||
builder.Services.AddTransient<IRequestMemberAccessService, RequestMemberAccessService>();
|
||||
builder.Services.AddTransient<ICurrentMemberClaimsProvider, CurrentMemberClaimsProvider>();
|
||||
|
||||
builder.AddUmbracoOpenApi();
|
||||
builder.AddUmbracoOpenApiDocument<ConfigureUmbracoDeliveryApiOpenApiOptions>(
|
||||
DeliveryApiConfiguration.ApiName,
|
||||
DeliveryApiConfiguration.ApiTitle,
|
||||
Constants.JsonOptionsNames.DeliveryApi);
|
||||
builder.Services.ConfigureOptions<ConfigureUmbracoDeliveryApiSwaggerGenOptions>();
|
||||
builder.AddUmbracoApiOpenApiUI();
|
||||
|
||||
builder
|
||||
.Services
|
||||
.AddControllers()
|
||||
.AddJsonOptions(
|
||||
Constants.JsonOptionsNames.DeliveryApi,
|
||||
options =>
|
||||
{
|
||||
// all Delivery API specific JSON options go here
|
||||
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||
options.JsonSerializerOptions.TypeInfoResolver = new DeliveryApiJsonTypeResolver();
|
||||
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
});
|
||||
|
||||
// Configures the JSON options for the Open API schema generation (based on the Delivery API MVC JSON options)
|
||||
builder.Services.ConfigureOptions<ConfigureUmbracoDeliveryHttpJsonOptions>();
|
||||
.AddJsonOptions(Constants.JsonOptionsNames.DeliveryApi, options =>
|
||||
{
|
||||
// all Delivery API specific JSON options go here
|
||||
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||
options.JsonSerializerOptions.TypeInfoResolver = new DeliveryApiJsonTypeResolver();
|
||||
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
});
|
||||
|
||||
builder.Services.AddAuthentication();
|
||||
builder.AddUmbracoOpenIddict();
|
||||
@@ -115,10 +105,6 @@ public static class UmbracoBuilderExtensions
|
||||
builder.AddNotificationAsyncHandler<MemberDeletedNotification, RevokeMemberAuthenticationTokensNotificationHandler>();
|
||||
builder.AddNotificationAsyncHandler<AssignedMemberRolesNotification, RevokeMemberAuthenticationTokensNotificationHandler>();
|
||||
builder.AddNotificationAsyncHandler<RemovedMemberRolesNotification, RevokeMemberAuthenticationTokensNotificationHandler>();
|
||||
builder.AddNotificationAsyncHandler<ExternalMemberSavedNotification, RevokeMemberAuthenticationTokensNotificationHandler>();
|
||||
builder.AddNotificationAsyncHandler<ExternalMemberDeletedNotification, RevokeMemberAuthenticationTokensNotificationHandler>();
|
||||
builder.AddNotificationAsyncHandler<AssignedExternalMemberRolesNotification, RevokeMemberAuthenticationTokensNotificationHandler>();
|
||||
builder.AddNotificationAsyncHandler<RemovedExternalMemberRolesNotification, RevokeMemberAuthenticationTokensNotificationHandler>();
|
||||
|
||||
// FIXME: remove this when Delivery API V1 is removed
|
||||
builder.Services.AddSingleton<MatcherPolicy, DeliveryApiItemsEndpointsMatcherPolicy>();
|
||||
@@ -146,7 +132,7 @@ public static class UmbracoBuilderExtensions
|
||||
{
|
||||
options.AddPolicy(
|
||||
Constants.DeliveryApi.OutputCache.ContentCachePolicy,
|
||||
new DeliveryApiOutputCacheContentPolicy(
|
||||
new DeliveryApiOutputCachePolicy(
|
||||
outputCacheSettings.ContentDuration,
|
||||
new StringValues([Constants.DeliveryApi.HeaderNames.AcceptLanguage, Constants.DeliveryApi.HeaderNames.AcceptSegment, Constants.DeliveryApi.HeaderNames.StartItem])));
|
||||
}
|
||||
@@ -155,30 +141,13 @@ public static class UmbracoBuilderExtensions
|
||||
{
|
||||
options.AddPolicy(
|
||||
Constants.DeliveryApi.OutputCache.MediaCachePolicy,
|
||||
new DeliveryApiOutputCacheMediaPolicy(
|
||||
new DeliveryApiOutputCachePolicy(
|
||||
outputCacheSettings.MediaDuration,
|
||||
Constants.DeliveryApi.HeaderNames.StartItem));
|
||||
}
|
||||
});
|
||||
|
||||
// Register eviction handlers.
|
||||
builder.AddNotificationAsyncHandler<ContentCacheRefresherNotification, DeliveryApiDocumentOutputCacheEvictionHandler>();
|
||||
builder.AddNotificationAsyncHandler<MediaCacheRefresherNotification, DeliveryApiMediaOutputCacheEvictionHandler>();
|
||||
builder.AddNotificationAsyncHandler<MemberCacheRefresherNotification, DeliveryApiMemberOutputCacheEvictionHandler>();
|
||||
builder.AddNotificationAsyncHandler<ElementCacheRefresherNotification, DeliveryApiElementOutputCacheEvictionHandler>();
|
||||
|
||||
// Register extension point default implementations.
|
||||
builder.Services.AddSingleton<IDeliveryApiOutputCacheTagProvider, DeliveryApiContentTypeOutputCacheTagProvider>();
|
||||
builder.Services.AddUnique<IDeliveryApiOutputCacheRequestFilter, DefaultDeliveryApiOutputCacheRequestFilter>();
|
||||
builder.Services.AddUnique<IDeliveryApiOutputCacheManager, DeliveryApiOutputCacheManager>();
|
||||
|
||||
// Signal that Umbraco has enabled output caching so the application builder registers
|
||||
// the output cache middleware. Gated via a marker rather than IOutputCacheStore so that
|
||||
// applications calling services.AddOutputCache(...) for their own purposes are not
|
||||
// affected by Umbraco's automatic middleware registration.
|
||||
builder.Services.TryAddSingleton<IUmbracoManagedOutputCacheMarker, UmbracoManagedOutputCacheMarker>();
|
||||
|
||||
builder.Services.Configure<UmbracoPipelineOptions>(options => options.AddFilter(new OutputCachePipelineFilter("UmbracoDeliveryApiOutputCache")));
|
||||
return builder;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Cms.Api.Delivery.Configuration;
|
||||
using Umbraco.Cms.Api.Delivery.Controllers.Content;
|
||||
using Umbraco.Cms.Core;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Filters;
|
||||
|
||||
internal sealed class SwaggerContentDocumentationFilter : SwaggerDocumentationFilterBase<ContentApiControllerBase>
|
||||
{
|
||||
protected override string DocumentationLink => DeliveryApiConfiguration.ApiDocumentationContentArticleLink;
|
||||
|
||||
protected override void ApplyOperation(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||
|
||||
AddExpand(operation, context);
|
||||
|
||||
AddFields(operation, context);
|
||||
|
||||
operation.Parameters.Add(new OpenApiParameter
|
||||
{
|
||||
Name = Constants.DeliveryApi.HeaderNames.AcceptLanguage,
|
||||
In = ParameterLocation.Header,
|
||||
Required = false,
|
||||
Description = "Defines the language to return. Use this when querying language variant content items.",
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
Examples = new Dictionary<string, IOpenApiExample>
|
||||
{
|
||||
{ "Default", new OpenApiExample { Value = string.Empty } },
|
||||
{ "English culture", new OpenApiExample { Value = "en-us" } },
|
||||
},
|
||||
});
|
||||
|
||||
operation.Parameters.Add(new OpenApiParameter
|
||||
{
|
||||
Name = Constants.DeliveryApi.HeaderNames.AcceptSegment,
|
||||
In = ParameterLocation.Header,
|
||||
Required = false,
|
||||
Description = "Defines the segment to return. Use this when querying segment variant content items.",
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
Examples = new Dictionary<string, IOpenApiExample>
|
||||
{
|
||||
{ "Default", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Segment One", new OpenApiExample { Value = "segment-one" } },
|
||||
},
|
||||
});
|
||||
|
||||
AddApiKey(operation);
|
||||
|
||||
operation.Parameters.Add(new OpenApiParameter
|
||||
{
|
||||
Name = Constants.DeliveryApi.HeaderNames.Preview,
|
||||
In = ParameterLocation.Header,
|
||||
Required = false,
|
||||
Description = "Whether to request draft content.",
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.Boolean },
|
||||
});
|
||||
|
||||
operation.Parameters.Add(new OpenApiParameter
|
||||
{
|
||||
Name = Constants.DeliveryApi.HeaderNames.StartItem,
|
||||
In = ParameterLocation.Header,
|
||||
Required = false,
|
||||
Description = "URL segment or GUID of a root content item.",
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
});
|
||||
}
|
||||
|
||||
protected override void ApplyParameter(OpenApiParameter parameter, ParameterFilterContext context)
|
||||
{
|
||||
switch (parameter.Name)
|
||||
{
|
||||
case "fetch":
|
||||
AddQueryParameterDocumentation(parameter, FetchQueryParameterExamples(), "Specifies the content items to fetch");
|
||||
break;
|
||||
case "filter":
|
||||
AddQueryParameterDocumentation(parameter, FilterQueryParameterExamples(), "Defines how to filter the fetched content items");
|
||||
break;
|
||||
case "sort":
|
||||
AddQueryParameterDocumentation(parameter, SortQueryParameterExamples(), "Defines how to sort the found content items");
|
||||
break;
|
||||
case "skip":
|
||||
parameter.Description = PaginationDescription(true, "content");
|
||||
break;
|
||||
case "take":
|
||||
parameter.Description = PaginationDescription(false, "content");
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private Dictionary<string, IOpenApiExample> FetchQueryParameterExamples() =>
|
||||
new()
|
||||
{
|
||||
{ "Select all", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Select all ancestors of a node by id", new OpenApiExample { Value = "ancestors:id" } },
|
||||
{ "Select all ancestors of a node by path", new OpenApiExample { Value = "ancestors:path" } },
|
||||
{ "Select all children of a node by id", new OpenApiExample { Value = "children:id" } },
|
||||
{ "Select all children of a node by path", new OpenApiExample { Value = "children:path" } },
|
||||
{ "Select all descendants of a node by id", new OpenApiExample { Value = "descendants:id" } },
|
||||
{ "Select all descendants of a node by path", new OpenApiExample { Value = "descendants:path" } },
|
||||
};
|
||||
|
||||
private Dictionary<string, IOpenApiExample> FilterQueryParameterExamples() =>
|
||||
new()
|
||||
{
|
||||
{ "Default filter", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Filter by content type (equals)", new OpenApiExample { Value = new JsonArray { "contentType:alias1" } } },
|
||||
{ "Filter by name (contains)", new OpenApiExample { Value = new JsonArray { "name:nodeName" } } },
|
||||
{ "Filter by creation date (less than)", new OpenApiExample { Value = new JsonArray { "createDate<2024-01-01" } } },
|
||||
{ "Filter by update date (greater than or equal)", new OpenApiExample { Value = new JsonArray { "updateDate>:2023-01-01" } } },
|
||||
};
|
||||
|
||||
private Dictionary<string, IOpenApiExample> SortQueryParameterExamples() =>
|
||||
new()
|
||||
{
|
||||
{ "Default sort", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Sort by create date", new OpenApiExample { Value = new JsonArray { "createDate:asc", "createDate:desc" } } },
|
||||
{ "Sort by level", new OpenApiExample { Value = new JsonArray { "level:asc", "level:desc" } } },
|
||||
{ "Sort by name", new OpenApiExample { Value = new JsonArray { "name:asc", "name:desc" } } },
|
||||
{ "Sort by sort order", new OpenApiExample { Value = new JsonArray { "sortOrder:asc", "sortOrder:desc" } } },
|
||||
{ "Sort by update date", new OpenApiExample { Value = new JsonArray { "updateDate:asc", "updateDate:desc" } } },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Cms.Core;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Filters;
|
||||
|
||||
internal abstract class SwaggerDocumentationFilterBase<TBaseController>
|
||||
: SwaggerFilterBase<TBaseController>, IOperationFilter, IParameterFilter
|
||||
where TBaseController : Controller
|
||||
{
|
||||
protected abstract string DocumentationLink { get; }
|
||||
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
if (CanApply(context))
|
||||
{
|
||||
ApplyOperation(operation, context);
|
||||
}
|
||||
}
|
||||
|
||||
public void Apply(IOpenApiParameter parameter, ParameterFilterContext context)
|
||||
{
|
||||
if (CanApply(context) && parameter is OpenApiParameter openApiParameter)
|
||||
{
|
||||
ApplyParameter(openApiParameter, context);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract void ApplyOperation(OpenApiOperation operation, OperationFilterContext context);
|
||||
|
||||
protected abstract void ApplyParameter(OpenApiParameter parameter, ParameterFilterContext context);
|
||||
|
||||
protected void AddQueryParameterDocumentation(OpenApiParameter parameter, Dictionary<string, IOpenApiExample> examples, string description)
|
||||
{
|
||||
parameter.Description = QueryParameterDescription(description);
|
||||
parameter.Examples = examples;
|
||||
}
|
||||
|
||||
protected void AddExpand(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
if (IsApiV1(context))
|
||||
{
|
||||
AddExpandV1(operation);
|
||||
}
|
||||
else
|
||||
{
|
||||
AddExpand(operation);
|
||||
}
|
||||
}
|
||||
|
||||
protected void AddFields(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
if (IsApiV1(context))
|
||||
{
|
||||
// "fields" is not a thing in Delivery API V1
|
||||
return;
|
||||
}
|
||||
|
||||
AddFields(operation);
|
||||
}
|
||||
|
||||
protected void AddApiKey(OpenApiOperation operation)
|
||||
{
|
||||
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||
operation.Parameters.Add(
|
||||
new OpenApiParameter
|
||||
{
|
||||
Name = Constants.DeliveryApi.HeaderNames.ApiKey,
|
||||
In = ParameterLocation.Header,
|
||||
Required = false,
|
||||
Description = "API key specified through configuration to authorize access to the API.",
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
});
|
||||
}
|
||||
|
||||
protected string PaginationDescription(bool skip, string itemType)
|
||||
=> $"Specifies the number of found {itemType} items to {(skip ? "skip" : "take")}. Use this to control pagination of the response.";
|
||||
|
||||
private string QueryParameterDescription(string description)
|
||||
=> $"{description}. Refer to [the documentation]({DocumentationLink}#query-parameters) for more details on this.";
|
||||
|
||||
// FIXME: remove this when Delivery API V1 has been removed (expectedly in V15)
|
||||
private static bool IsApiV1(OperationFilterContext context)
|
||||
=> context.ApiDescription.RelativePath?.Contains("api/v1") is true;
|
||||
|
||||
// FIXME: remove this when Delivery API V1 has been removed (expectedly in V15)
|
||||
private void AddExpandV1(OpenApiOperation operation)
|
||||
{
|
||||
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||
operation.Parameters.Add(
|
||||
new OpenApiParameter
|
||||
{
|
||||
Name = "expand",
|
||||
In = ParameterLocation.Query,
|
||||
Required = false,
|
||||
Description =
|
||||
QueryParameterDescription("Defines the properties that should be expanded in the response"),
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
Examples = new Dictionary<string, IOpenApiExample>
|
||||
{
|
||||
{ "Expand none", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Expand all", new OpenApiExample { Value = "all" } },
|
||||
{ "Expand specific property", new OpenApiExample { Value = "property:alias1" } },
|
||||
{ "Expand specific properties", new OpenApiExample { Value = "property:alias1,alias2" } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private void AddExpand(OpenApiOperation operation)
|
||||
{
|
||||
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||
operation.Parameters.Add(
|
||||
new OpenApiParameter
|
||||
{
|
||||
Name = "expand",
|
||||
In = ParameterLocation.Query,
|
||||
Required = false,
|
||||
Description =
|
||||
QueryParameterDescription("Defines the properties that should be expanded in the response"),
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
Examples = new Dictionary<string, IOpenApiExample>
|
||||
{
|
||||
{ "Expand none", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Expand all properties", new OpenApiExample { Value = "properties[$all]" } },
|
||||
{ "Expand specific property", new OpenApiExample { Value = "properties[alias1]" } },
|
||||
{ "Expand specific properties", new OpenApiExample { Value = "properties[alias1,alias2]" } },
|
||||
{ "Expand nested properties", new OpenApiExample { Value = "properties[alias1[properties[nestedAlias1,nestedAlias2]]]" } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private void AddFields(OpenApiOperation operation)
|
||||
{
|
||||
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||
operation.Parameters.Add(
|
||||
new OpenApiParameter
|
||||
{
|
||||
Name = "fields",
|
||||
In = ParameterLocation.Query,
|
||||
Required = false,
|
||||
Description =
|
||||
QueryParameterDescription(
|
||||
"Explicitly defines which properties should be included in the response (by default all properties are included)"),
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
Examples = new Dictionary<string, IOpenApiExample>
|
||||
{
|
||||
{ "Include all properties", new OpenApiExample { Value = "properties[$all]" } },
|
||||
{ "Include only specific property", new OpenApiExample { Value = "properties[alias1]" } },
|
||||
{ "Include only specific properties", new OpenApiExample { Value = "properties[alias1,alias2]" } },
|
||||
{ "Include only specific nested properties", new OpenApiExample { Value = "properties[alias1[properties[nestedAlias1,nestedAlias2]]]" } },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Filters;
|
||||
|
||||
internal abstract class SwaggerFilterBase<TBaseController>
|
||||
where TBaseController : Controller
|
||||
{
|
||||
protected bool CanApply(OperationFilterContext context)
|
||||
=> CanApply(context.MethodInfo);
|
||||
|
||||
protected bool CanApply(ParameterFilterContext context)
|
||||
=> CanApply(context.ParameterInfo.Member);
|
||||
|
||||
private bool CanApply(MemberInfo member)
|
||||
=> member.DeclaringType?.Implements<TBaseController>() is true;
|
||||
}
|
||||
+19
-33
@@ -1,41 +1,27 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Umbraco.Cms.Api.Delivery.Configuration;
|
||||
using Umbraco.Cms.Api.Delivery.Controllers.Media;
|
||||
using Umbraco.Extensions;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.OpenApi.Transformers;
|
||||
namespace Umbraco.Cms.Api.Delivery.Filters;
|
||||
|
||||
/// <summary>
|
||||
/// Transforms OpenAPI operations for the Media API, adding relevant parameters and documentation.
|
||||
/// </summary>
|
||||
internal sealed class MediaApiTransformer : DeliveryApiTransformerBase
|
||||
internal sealed class SwaggerMediaDocumentationFilter : SwaggerDocumentationFilterBase<MediaApiControllerBase>
|
||||
{
|
||||
protected override string DocumentationLink => DeliveryApiConfiguration.ApiDocumentationMediaArticleLink;
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override bool ShouldApply(OpenApiOperationTransformerContext context) =>
|
||||
context.Description.ActionDescriptor is ControllerActionDescriptor description
|
||||
&& description.ControllerTypeInfo.Implements<MediaApiControllerBase>();
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override Task ApplyAsync(
|
||||
OpenApiOperation operation,
|
||||
OpenApiOperationTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
protected override void ApplyOperation(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||
foreach (OpenApiParameter parameter in operation.Parameters?.OfType<OpenApiParameter>() ?? [])
|
||||
{
|
||||
ApplyParameter(parameter);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
AddExpand(operation, context);
|
||||
|
||||
AddFields(operation, context);
|
||||
|
||||
AddApiKey(operation);
|
||||
}
|
||||
|
||||
private void ApplyParameter(OpenApiParameter parameter)
|
||||
protected override void ApplyParameter(OpenApiParameter parameter, ParameterFilterContext context)
|
||||
{
|
||||
switch (parameter.Name)
|
||||
{
|
||||
@@ -70,18 +56,18 @@ internal sealed class MediaApiTransformer : DeliveryApiTransformerBase
|
||||
private Dictionary<string, IOpenApiExample> FilterQueryParameterExamples() =>
|
||||
new()
|
||||
{
|
||||
{ "Default filter", new OpenApiExample { Value = new JsonArray(string.Empty) } },
|
||||
{ "Filter by media type", new OpenApiExample { Value = new JsonArray("mediaType:alias1") } },
|
||||
{ "Filter by name", new OpenApiExample { Value = new JsonArray("name:nodeName") } },
|
||||
{ "Default filter", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Filter by media type", new OpenApiExample { Value = new JsonArray { "mediaType:alias1" } } },
|
||||
{ "Filter by name", new OpenApiExample { Value = new JsonArray { "name:nodeName" } } },
|
||||
};
|
||||
|
||||
private Dictionary<string, IOpenApiExample> SortQueryParameterExamples() =>
|
||||
new()
|
||||
{
|
||||
{ "Default sort", new OpenApiExample { Value = new JsonArray(string.Empty) } },
|
||||
{ "Sort by create date", new OpenApiExample { Value = new JsonArray("createDate:asc", "createDate:desc") } },
|
||||
{ "Sort by name", new OpenApiExample { Value = new JsonArray("name:asc", "name:desc") } },
|
||||
{ "Sort by sort order", new OpenApiExample { Value = new JsonArray("sortOrder:asc", "sortOrder:desc") } },
|
||||
{ "Sort by update date", new OpenApiExample { Value = new JsonArray("updateDate:asc", "updateDate:desc") } },
|
||||
{ "Default sort", new OpenApiExample { Value = string.Empty } },
|
||||
{ "Sort by create date", new OpenApiExample { Value = new JsonArray { "createDate:asc", "createDate:desc" } } },
|
||||
{ "Sort by name", new OpenApiExample { Value = new JsonArray { "name:asc", "name:desc" } } },
|
||||
{ "Sort by sort order", new OpenApiExample { Value = new JsonArray { "sortOrder:asc", "sortOrder:desc" } } },
|
||||
{ "Sort by update date", new OpenApiExample { Value = new JsonArray { "updateDate:asc", "updateDate:desc" } } },
|
||||
};
|
||||
}
|
||||
+1
-66
@@ -5,7 +5,6 @@ using Umbraco.Cms.Core.Configuration.Models;
|
||||
using Umbraco.Cms.Core.Events;
|
||||
using Umbraco.Cms.Core.Models;
|
||||
using Umbraco.Cms.Core.Notifications;
|
||||
using Umbraco.Cms.Core.Security;
|
||||
using Umbraco.Cms.Core.Services;
|
||||
|
||||
namespace Umbraco.Cms.Api.Delivery.Handlers;
|
||||
@@ -14,11 +13,7 @@ internal sealed class RevokeMemberAuthenticationTokensNotificationHandler
|
||||
: INotificationAsyncHandler<MemberSavedNotification>,
|
||||
INotificationAsyncHandler<MemberDeletedNotification>,
|
||||
INotificationAsyncHandler<AssignedMemberRolesNotification>,
|
||||
INotificationAsyncHandler<RemovedMemberRolesNotification>,
|
||||
INotificationAsyncHandler<ExternalMemberSavedNotification>,
|
||||
INotificationAsyncHandler<ExternalMemberDeletedNotification>,
|
||||
INotificationAsyncHandler<AssignedExternalMemberRolesNotification>,
|
||||
INotificationAsyncHandler<RemovedExternalMemberRolesNotification>
|
||||
INotificationAsyncHandler<RemovedMemberRolesNotification>
|
||||
{
|
||||
private readonly IMemberService _memberService;
|
||||
private readonly IOpenIddictTokenManager _tokenManager;
|
||||
@@ -85,38 +80,6 @@ internal sealed class RevokeMemberAuthenticationTokensNotificationHandler
|
||||
}
|
||||
}
|
||||
|
||||
public async Task HandleAsync(ExternalMemberSavedNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_enabled is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (ExternalMemberIdentity member in notification.SavedEntities.Where(m => m.IsLockedOut || m.IsApproved is false))
|
||||
{
|
||||
await RevokeTokensByKeyAsync(member.Key);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task HandleAsync(ExternalMemberDeletedNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_enabled is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (ExternalMemberIdentity member in notification.DeletedEntities)
|
||||
{
|
||||
await RevokeTokensByKeyAsync(member.Key);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task HandleAsync(AssignedExternalMemberRolesNotification notification, CancellationToken cancellationToken)
|
||||
=> await ExternalMemberRolesChangedAsync(notification);
|
||||
|
||||
public async Task HandleAsync(RemovedExternalMemberRolesNotification notification, CancellationToken cancellationToken)
|
||||
=> await ExternalMemberRolesChangedAsync(notification);
|
||||
|
||||
private async Task MemberRolesChangedAsync(MemberRolesNotification notification)
|
||||
{
|
||||
if (_enabled is false)
|
||||
@@ -136,32 +99,4 @@ internal sealed class RevokeMemberAuthenticationTokensNotificationHandler
|
||||
await RevokeTokensAsync(member);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExternalMemberRolesChangedAsync(ExternalMemberRolesNotification notification)
|
||||
{
|
||||
if (_enabled is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (Guid memberKey in notification.MemberKeys)
|
||||
{
|
||||
await RevokeTokensByKeyAsync(memberKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RevokeTokensByKeyAsync(Guid memberKey)
|
||||
{
|
||||
var tokens = await _tokenManager.FindBySubjectAsync(memberKey.ToString()).ToArrayAsync();
|
||||
if (tokens.Any() is false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Revoking {count} active tokens for external member with key {key}", tokens.Length, memberKey);
|
||||
foreach (var token in tokens)
|
||||
{
|
||||
await _tokenManager.DeleteAsync(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ public abstract class DeliveryApiVersionAwareJsonConverterBase<T> : JsonConverte
|
||||
private int? GetApiVersion()
|
||||
{
|
||||
HttpContext? httpContext = _httpContextAccessor.HttpContext;
|
||||
ApiVersion? apiVersion = httpContext?.RequestedApiVersion;
|
||||
ApiVersion? apiVersion = httpContext?.GetRequestedApiVersion();
|
||||
|
||||
return apiVersion?.MajorVersion;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user