Created
November 24, 2023 15:51
-
-
Save steliodibello/b29f4aedf57b1ef8e8951d6e3d476389 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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