Skip to content

Instantly share code, notes, and snippets.

@steliodibello
Created November 24, 2023 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steliodibello/b29f4aedf57b1ef8e8951d6e3d476389 to your computer and use it in GitHub Desktop.
Save steliodibello/b29f4aedf57b1ef8e8951d6e3d476389 to your computer and use it in GitHub Desktop.
namespace XXXCUSTOM.Middleware
{
using Microsoft.AspNetCore.Http;
using Sitecore.AspNet.RenderingEngine;
using Sitecore.LayoutService.Client.Response.Model;
using Sitecore.LayoutService.Client.Response.Model.Fields;
using System.Threading.Tasks;
public class RedirMiddleware
{
private const string RedirectTemplateID = "XXXX-XXXX-XXXX-XXX-XXXX";
public RedirectMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var custrequest = context.GetSitecoreRenderingContext();
var custroute = custrequest.Response?.Content?.Sitecore?.Route;
if (custroute == null)
{
await _next(context);
}
if (!IsRedirect(route, context))
{
await _next(context);
}
}
private bool IsRedirect(Route route, HttpContext context)
{
//RUN Redirect LOGIC!!!
if (route == null)
{
return false;
}
if (route.TemplateId != RedirectTemplateID)
{
return false;
}
var isPermanent = false;
var redirectType = route.ReadField<ItemLinkField>("Response Status Code");
if (redirectType != null)
{
if (redirectType.Url != null)
{
if (redirectType.Url.Contains("301"))
{
isPermanent = true;
}
}
}
var redirectTextField = route.ReadField<TextField>("Redirect To Url");
if (!string.IsNullOrEmpty(redirectTextField.Value))
{
context.Response.Redirect(redirectTextField.Value, isPermanent);
return true;
}
var destinationField = route.ReadField<ItemLinkField>("Redirect To Item");
var destinationUrl = destinationField?.Url;
if (!string.IsNullOrEmpty(destinationUrl))
{
context.Response.Redirect(destinationUrl, isPermanent);
return true;
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment