Copied to clipboard

Flag this post as spam?

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


  • Christopher Crawford 5 posts 109 karma points
    Jan 09, 2017 @ 00:31
    Christopher Crawford
    0

    301 Redirect Programmatically?

    Hello,

    I was wondering if there was any way to create a 301 redirect programmatically? I'm currently in a situation of needing to create sites from a .csv data source and one of the columns is a "vanityUrl" that when traveled to will complete a 301 redirect.

    For example:

    Id,data,vanityUrl
    1,{...},http://mysite.com/myvanityurl
    

    I take a data set like that, copy/create the node I need using the IContentService like so:

    var newNode = _contentService.Copy(_globalContent, parent.Id, true);
    if(newNode.HasProperty("currentProperty")
        newNode.SetValue("currentProperty", value);
    
    // I want to do something like so
    // newNode.Set301Redirect("http://mysite.com/myvanityurl")
    // or-----
    // IUrlRedirectService urlService = ApplicationContext.Current.Services.RedirectUrlService;
    // urlService.Register(newNode.Url, "http://mysite.con/myvanityurl", {guid});
    
    _contentService.Save(newNode);
    

    Listed above in the code snippet is generally what I would like to accomplish. In reading through the forums, it mostly shows solutions that are solved via web.config updates, however I'm not sure that would work in this scenario as I do not know the values until I parse all the data and generate the site.

    This following package looks like it could help, but I'm unsure of how to utilize that in my project or if it can accomplish this programmatically:

    https://github.com/kipusoep/UrlTracker

    Any help would be greatly appreciated.

  • Ben Gdovicak 5 posts 34 karma points
    Jan 09, 2017 @ 12:04
    Ben Gdovicak
    0

    I to have looked around quite a bit and have been unsuccessful in finding how to set 301's via the api's. Any information on this would be really helpful.

  • Christopher Crawford 5 posts 109 karma points
    Jan 09, 2017 @ 16:18
    Christopher Crawford
    101

    I have fixed my issue -- seems that I was trying to use the wrong Guid on the content node in question (was using PublishedVersion and Version guids on the node). The solution was to use the IRedirectUrlService.

    The working code is as follows:

    var trimmedVanityUrl = vanityUrlSplit.Skip(3).Aggregate((current, next) => current + "/" + next);
    var fullVanityUrl = "/" + trimmedVanityUrl;
    _urlRedirectService.Register(fullVanityUrl, newNode.Key);
    

    This vanityUrl gets converted from the data source into a relative url (eg: /mycoolurl/sweet). When traversing to localhost:52153/mycoolurl/sweet, I get the proper 301 redirect to the "newNode".

Please Sign in or register to post replies

Write your reply to:

Draft