Copied to clipboard

Flag this post as spam?

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


  • Martin Rud 260 posts 1001 karma points c-trib
    May 18, 2023 @ 11:23
    Martin Rud
    0

    How to make 301 redirect in Umbraco 9+ / a .NET Core view?

    I have Umbraco 11 and in the navigation editors can add Multi Url Picker items (doc type "ExternalUrl"). This is used for having navigation items pointing to external url or media items.

    When rendering the navigation I make sure to check if the item is doc type "ExternalUrl" and change the href accordingly:

    var linkTo = item.Value<Link>("linkTo");
    string href = linkTo != null ? linkTo.Url : item.Url(PublishedUrlProvider);
    

    But I would like to handle visitors visiting the url, i.e. www.mydomain.com/my/external/url/document

    Therefore: In my ExternalUrl.cshtml template, how should I do that?

    For now I have made i JavaScript, but thats not very SEO friendly:

    @inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage
    @using Umbraco.Cms.Core.Models;
    @{
        Layout = null;
        var linkTo = Model.Value<Link>("linkTo");
        if (linkTo != null)
        {
            <p>Redirecting to @linkTo.Url ...</p>
    
    
    <script type="text/javascript">
                window.location.href = '@linkTo.Url';
            </script>
    
    
        }
    }
    
  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    May 19, 2023 @ 07:54
    Huw Reddick
    100

    Hi Martin,

    Ideally you should be doing this either in a controller or with some middleware, you really shouldn't be redirecting from a view.

    If you really must then you could just do a response .redirect

    @{ 
        if (linkTo != null)
        {
            Context.Response.Redirect(linkTo.Url);
            return;
        }
    }
    

    The return is important.

  • Martin Rud 260 posts 1001 karma points c-trib
    May 19, 2023 @ 09:25
    Martin Rud
    0

    Cool, thanks.

    I will use the above since there is only one page in the solution that uses it and no one really ever should "meet" the template since there is no links to the "page"

Please Sign in or register to post replies

Write your reply to:

Draft