Skip to content

Instantly share code, notes, and snippets.

@KevinJump
Last active February 20, 2022 11:57
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 KevinJump/5a44a8a47cdc3e9521d13141ef3ee70c to your computer and use it in GitHub Desktop.
Save KevinJump/5a44a8a47cdc3e9521d13141ef3ee70c to your computer and use it in GitHub Desktop.
change umbraco content in middleware (example, may need some work!)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Web.Common.ApplicationBuilder;
namespace MiddleLib
{
/// <summary>
/// example of how to replace content in middleware in umbraco
/// (for example if you want to put under maintance page up ?
/// </summary>
public class MyComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.Configure<UmbracoPipelineOptions>(options =>
{
options.AddFilter(new UmbracoPipelineFilter(
"MaintainTemplate",
applicationBuilder =>
{
applicationBuilder.UseWhen(
ctx => !IsBackendRequest(ctx.Request.Path),
ab => ab.UseMiddleware<MaintainTemplateMiddleWare>());
},
applicationBuilder => { },
applicationBuilder => { }
));
});
}
private static string[] backofficePaths = new string[]
{
"/umbraco",
"/App_Plugins",
"/api", // keep alive ??
"/media" // let media through ? (because of the back office???)
};
private bool IsBackendRequest(PathString path)
{
foreach (var backofficepath in backofficePaths) {
if (path.StartsWithSegments(backofficepath))
return true;
}
return false;
}
}
public class MaintainTemplateMiddleWare
{
private readonly RequestDelegate _next;
private readonly IConfiguration _config;
private ILogger<MaintainTemplateMiddleWare> _logger;
public MaintainTemplateMiddleWare(RequestDelegate next,
IConfiguration config,
ILogger<MaintainTemplateMiddleWare> logger)
{
_next = next;
_logger = logger;
_config = config;
_logger.LogInformation("Starting middleware");
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation("Middleware tiggered {url}", context.Request.Path);
if (_config.GetValue<bool>("Maintain:Enabled", false))
{
using (var stream = GetTemplate())
{
await stream.CopyToAsync(context.Response.Body);
}
}
else
{
await _next(context);
}
}
private Stream GetTemplate()
{
var text = "<h1>Maintenance Template</h1>";
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(text);
writer.Flush();
stream.Position = 0;
return stream;
}
}
}
@KevinJump
Copy link
Author

Note - one does not simple set the body content .... you have to copy into it. see https://stackoverflow.com/a/58688017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment