Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • claudio morandi 24 posts 92 karma points
    Feb 18, 2025 @ 08:33
    claudio morandi
    0

    How to get a media by url without hitting the database?

    Hello... I need to correct a middleware that checks a media property for each request. It's currenlty working but it tells me that the method I use is obsolete and will be removed on next version (14) of Umbraco.

    I should obtain a media by its url but without hitting the db. Can you help me?

    I currently use this code

    IPublishedMediaCache? mediaCache = umbracoContextReference.UmbracoContext.Media;

    var foundMedia = mediaCache.GetSingleByXPath($"//umbracoFile[contains(., '{context.Request.Path}')]");

    Thank you so much

  • Sam Marshallsay 37 posts 137 karma points
    Feb 19, 2025 @ 16:28
    Sam Marshallsay
    0

    You could probably just get all descendants with umbracohelper and filter them with LINQ. Something like:

    var matchingMedia = _uh.MediaAtRoot().SelectMany(x => x.DescendantsOrSelf()).FirstOrDefault(x => x.Value<string>("umbracoFile").Contains("request-path-here"));
    

    And tweak it a bit to ignore case etc

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies