Search code examples
c#.netepiserveroptimizely

Episerver: How do I use the GetBySegment-method?


I've heard that the GetBySegment() method in Episerver has better performance than using GetChildren().FirstOrDefault(). But I have trouble wrapping my head around the usage of the method.

Let's imagine I have a simple method like this. It is supposed to get a page type of which there are only supposed to be one on the website so the "FirstByDefault() always returns the same page. However, the location, name, or the url might be different based on the environment:

public virtual PageTypeA GetPageTypeA()
{
    var pageTypeA = _contentLoader.GetChildren<PageTypeA>(rootPageReference).FirstOrDefault();

    return pageTypeA;
}

Is it possible to replace the "GetChildren().FirstOrDefault()" here with the GetBySegment() method. As I understand it, the GetBySegment() requires a urlSegment string, but I don't want to "hardcode" it in, because as I said, the location, name, or the url can vary based on the environment. So how would I use the GetBySegment() or is it even possible to use it here?

What I've tried are "hardcoding" the urlSegement in to the GetBySegement, and it will find the page, but I can't do it that way for the reasons I described earlier.


Solution

  • I did not know GetBySegment but have looked at the documentation, code and comments. You are comparing apples with pears. Both methods cannot be used interchangeably.

    • ContentLoader/ContentRepository.GetChildren<T> returns all content of a given type under a given parent in the given langage or LoaderOptions(if provided)
    • ContentLoader/ContentRepository.GetBySegment returns the single content under a given parent with a given RouteSegment(for example provided via page's "Name in URL"). The provided LoaderOptions(for example the language you want to use) IS IGNORED, until there is only one match. This is intended. So the loader-options are just used to find the best match.

    So use GetChildren if you want to get all children under a parent in a given language. Use GetBySegment if you want exactly one match and all you care about is the RouteSegment of it.

    Regarding performance: GetChildren is cached, so there should be no impact on the second call, especially because FirstOrDefault is basically a no-op.