Orchardcore media

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore media is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for managing media in Orchard Core. Covers the OrchardCore Media configuration section, MediaOptions, allowed and restricted file extensions, UploadRestrictedMedia, tenant-contained AssetsPath, temporary upload storage, on-demand image resizing with the NetVips engine, custom IImageProcessingE

How to use this skill

Skill file

Orchard Core Media

Guidelines

Features

| Feature ID | Purpose |

|---|---|

| OrchardCore.Media | Media library, resizing, profiles, MediaField, Media API. |

| OrchardCore.Media.Cache | Local cache of remote (Azure/S3) files; enabled by the cloud storage features. |

| OrchardCore.Media.Security | Secure Media, folder-level view permissions. |

| OrchardCore.Media.Slugify | SEO-friendly file and folder names (orchardcore-media-slugify). |

| OrchardCore.Media.Tus | Resumable TUS uploads. |

| OrchardCore.Media.SignalR | Real-time gallery updates. |

| OrchardCore.Media.Indexing.Text, .Pdf, .OpenXML | Extract .txt/.md, .pdf, .docx/.pptx text from files referenced by media fields. |

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "OrchardCore.Media",
        "OrchardCore.Media.Indexing.Pdf"
      ],
      "disable": []
    }
  ]
}

Configuration (`OrchardCore:Media`)

{
  "OrchardCore": {
    "Media": {
      "MaxFileSize": 30000000,
      "CdnBaseUrl": "https://cdn.example.com",
      "AssetsRequestPath": "/media",
      "AssetsPath": "Media",
      "UseTokenizedQueryString": true,
      "SupportedSizes": [ 16, 32, 50, 100, 160, 240, 480, 600, 1024, 2048 ],
      "MaxBrowserCacheDays": 30,
      "MaxSecureFilesBrowserCacheDays": 0,
      "MaxCacheDays": 365,
      "AllowedFileExtensions": [ ".jpg", ".jpeg", ".png", ".gif", ".webp", ".pdf", ".docx", ".mp4" ],
      "RestrictedFileExtensions": [ ".css", ".js", ".svg" ],
      "ContentSecurityPolicy": "default-src 'self'; style-src 'unsafe-inline'",
      "MaxUploadChunkSize": 104857600,
      "TemporaryFileLifetime": "01:00:00",
      "DisableThumbnails": false
    }
  }
}

Upload size limits

services.Configure<KestrelServerOptions>(options => options.Limits.MaxRequestBodySize = 50_000_000);
services.Configure<IISServerOptions>(options => options.MaxRequestBodySize = 50_000_000);
services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 50_000_000);

On IIS also set <requestLimits maxAllowedContentLength="50000000" /> in

web.config.

Image Processing

Custom image processing engine

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using OrchardCore.Media.Processing;
using OrchardCore.Modules;

public sealed class MyImageProcessingEngine : IImageProcessingEngine
{
    public async Task<ImageProcessingResult> ProcessAsync(
        Stream input,
        ImageProcessingCommands commands,
        CancellationToken cancellationToken = default)
    {
        var output = new MemoryStream();

        // Resize "input" with your imaging library using commands.Width, commands.Height,
        // commands.ResizeMode, commands.Quality, commands.BackgroundColor and the focal point.
        await input.CopyToAsync(output, cancellationToken);
        output.Position = 0;

        return new ImageProcessingResult
        {
            Output = output,
            ContentType = "image/jpeg",
        };
    }
}

[RequireFeatures("OrchardCore.Media")]
public sealed class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.Replace(ServiceDescriptor.Singleton<IImageProcessingEngine, MyImageProcessingEngine>());
    }
}

A custom IResizedImageCache implements GetAsync(cacheKey, fileExtension),

SetAsync, ClearAsync and ClearStaleAsync, and is registered the same way.

Media Profiles

Create profiles under Media → Profiles (ManageMediaProfiles) or with the

MediaProfiles step. Mode is Max, Crop, Pad, BoxPad, Min or

Stretch; Format is Undefined, Jpg, Png, Gif or WebP.

{
  "steps": [
    {
      "name": "MediaProfiles",
      "MediaProfiles": {
        "thumbnail": {
          "Hint": "Square thumbnail for listings",
          "Width": 240,
          "Height": 240,
          "Mode": "Crop",
          "Format": "WebP",
          "Quality": 80,
          "BackgroundColor": "",
          "AutoOrient": true
        }
      }
    }
  ]
}

Profiles are exported with the All Media Profiles deployment step.

Rendering Media

Liquid

{{ Model.ContentItem.Content.Article.Image.Paths.first | asset_url | img_tag: alt: 'Cover' }}
{{ 'animals/kittens.jpg' | asset_url | resize_url: width: 400, height: 300, mode: 'crop' | img_tag }}
{{ 'animals/kittens.jpg' | asset_url | resize_url: width: 800, format: 'webp', quality: 75 }}
{{ 'animals/kittens.jpg' | asset_url | resize_url: profile: 'thumbnail' }}
{{ 'animals/kittens.jpg' | asset_url | append_version }}

{% assign anchor = Model.ContentItem.Content.Article.Image.Anchors.first %}
{{ 'animals/kittens.jpg' | asset_url | resize_url: width: 100, height: 240, mode: 'crop', anchor: anchor }}

Named and positional resize_url arguments cannot be mixed. bgcolor applies

to pad/boxpad.

Razor

Reference the OrchardCore.Media package from the theme or module and add

@addTagHelper *, OrchardCore.Media to _ViewImports.cshtml.

<img src="@Orchard.AssetUrl(Model.Paths[0], width: 400, height: 300, resizeMode: ResizeMode.Crop)" alt="" />
<img src="@await Orchard.AssetProfileUrlAsync(Model.Paths[0], "thumbnail")" alt="" />
<img asset-src="@Model.Paths[0]" alt="@Model.MediaTexts[0]" img-width="800" img-format="WebP" img-quality="75" asp-append-version="true" />
<img asset-src="@Model.Paths[0]" img-profile="thumbnail" img-anchor="@Model.Field.GetAnchors()[0]" alt="" />
<a asset-href="docs/brochure.pdf" target="_blank">Download</a>

MediaTexts[] and Anchors[] are index-aligned with Paths[].

Media Fields

MediaFieldSettings: Multiple, AllowMediaText, AllowAnchors,

AllowedExtensions (can only narrow the global lists), plus Hint/Required.

| Editor | Behavior |

|---|---|

| Standard (default) | Picks existing library files; Secure Media folder permissions apply. |

| Gallery | Same storage as Standard, with card/list views and drag-and-drop reordering. |

| Attached | Uploads into mediafields/{ContentType}/{ContentItemId}/ with hash-based names; requires ManageAttachedMediaFieldsFolder; with Secure Media, files follow the item's ViewContent. Supports TUS. |

await _contentDefinitionManager.AlterPartDefinitionAsync("Article", part => part
    .WithField("Attachments", field => field
        .OfType("MediaField")
        .WithDisplayName("Attachments")
        .WithEditor("Attached")
        .WithSettings(new MediaFieldSettings
        {
            Multiple = true,
            AllowMediaText = true,
            AllowedExtensions = [".pdf", ".docx"],
        })));

After switching existing fields to Attached, move the referenced files:

{
  "steps": [
    {
      "name": "move-attached-media-fields",
      "ContentTypes": [ "Article", "Report" ]
    }
  ]
}

Omit ContentTypes to process every type with an Attached media field. The

step runs in a background job and saves in batches of 50.

Importing Files (`media` step)

{
  "steps": [
    {
      "name": "media",
      "Files": [
        { "TargetPath": "images/logo.png", "SourcePath": "../wwwroot/images/logo.png" },
        { "TargetPath": "images/banner.jpg", "SourceUrl": "https://example.com/banner.jpg" },
        { "TargetPath": "docs/readme.txt", "Base64": "SGVsbG8=" }
      ]
    }
  ]
}

TargetPath (alias Path) must be a relative path inside the tenant media

store; rooted paths, drive prefixes, empty segments and ./.. segments are

rejected before anything is read or overwritten.

Permissions

| MediaPermissions member | Name | Notes |

|---|---|---|

| ManageMediaFolder | ManageMediaFolder | Broadest; implies all others below it and the Secure Media view permissions. |

| ManageOthersMedia | ManageOthersMediaContent | Implied by ManageMediaFolder. |

| ManageOwnMedia | ManageOwnMediaContent | Implied by ManageOthersMedia. |

| ManageAttachedMediaFieldsFolder | ManageAttachedMediaFieldsFolder | mediafields/ folder. |

| ManageMedia | ManageMediaContent | Minimum to open the library. |

| UploadRestrictedMedia | UploadRestrictedMedia | Restricted extensions. |

| ManageMediaProfiles | ManageMediaProfiles | Profiles. |

| ViewMediaOptions | ViewMediaOptions | Settings → Media → Options page. |

| ManageMediaApiSettings | ManageMediaApiSettings | Media API authentication scheme. |

| ManageAssetCache | ManageAssetCache | Remote media cache purge. |

| ViewMedia, ViewRootMedia, ViewOthersMedia, ViewOwnMedia | ViewMediaContent, ViewRootMediaContent, ViewOthersMediaContent, ViewOwnMediaContent | Only with Secure Media. |

if (!await _authorizationService.AuthorizeAsync(User, MediaPermissions.ManageMediaFolder, (object)"images/products"))
{
    return Forbid();
}

Secure Media (`OrchardCore.Media.Security`)

Media Events

using OrchardCore.Media.Events;

public sealed class MediaQuotaEventHandler : IMediaEventHandler
{
    public Task MediaPermittedStorageAsync(MediaPermittedStorageContext context)
    {
        context.Constrain(10L * 1024 * 1024 * 1024); // smallest limit wins
        return Task.CompletedTask;
    }

    public Task MediaCreatedFileAsync(MediaCreatedContext context)
    {
        // React to uploads, e.g. audit or notify.
        return Task.CompletedTask;
    }
}

public sealed class StripMetadataHandler : IMediaCreatingEventHandler
{
    public Task<Stream> MediaCreatingAsync(MediaCreatingContext context, Stream creatingStream)
        => Task.FromResult(creatingStream); // return a transformed stream to replace the upload
}

Register with services.AddScoped<IMediaEventHandler, MediaQuotaEventHandler>()

and services.AddScoped<IMediaCreatingEventHandler, StripMetadataHandler>().

IMediaEventHandler has default implementations for every method (deleting,

moving, copying, directory events). The plain

IMediaFileStore.CreateFileFromStreamAsync(path, stream) only runs

IMediaCreatingEventHandler. To also run the shared IFileEventHandler

pipeline (which orchardcore-antivirus uses to scan files), call the

CreateFileFromStreamAsync(fileCreationService, path, stream, ...) overload

from MediaFileStoreExtensions; see orchardcore-file-upload-security.

Media Indexing

Tick Include this element in the index on a media field; the index then gets

{Part}.{Field}.MediaText and, with an extraction feature, {Part}.{Field}.FileText.

Standalone library files that no media field references are not indexed.

Upgrading from 3.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.