Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 70 additions & 5 deletions PeachPied.WordPress.AspNetCore/Internal/WpResponseCaching.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
Expand All @@ -20,6 +25,8 @@ internal class WpResponseCacheMiddleware
readonly WpResponseCachePolicy _policy;
readonly ILogger _logger;
readonly IMemoryCache _cache;
readonly IHttpContextAccessor _contextAccessor;
readonly bool _enableRazor;

class CacheKey : IEquatable<CacheKey>
{
Expand Down Expand Up @@ -102,8 +109,8 @@ async Task<CachedPage> CaptureResponse(HttpContext context)

byte[] bytes;

// gzip response
if (ShouldCompressResponse(context))
// gzip response, dont use on _enableRazor
if (ShouldCompressResponse(context) && !_enableRazor)
{
context.Response.Headers.Append(HeaderNames.ContentEncoding, "gzip");
context.Response.Headers.Remove(HeaderNames.ContentMD5); // Reset the MD5 because the content changed.
Expand All @@ -126,10 +133,26 @@ async Task<CachedPage> CaptureResponse(HttpContext context)
var cached = IsResponseCacheable(context) ? new CachedPage(context, bytes) : null;

//
await responseStream.WriteAsync(bytes, 0, bytes.Length);
if (!_enableRazor)
{
await responseStream.WriteAsync(bytes, 0, bytes.Length);
}

return cached;
}

public bool ShouldUseRazor()
{
if (_enableRazor &&
!_contextAccessor.HttpContext.Request.Path.ToString().Contains("wp-content/") &&
!_contextAccessor.HttpContext.Request.Path.ToString().Contains("wp-includes/") &&
!_contextAccessor.HttpContext.Request.Path.ToString().Contains("wp-admin/"))
{
return true;
}
return false;
}

static bool ShouldCompressResponse(HttpContext context)
{
if (context.Response.Headers.ContainsKey(HeaderNames.ContentRange))
Expand Down Expand Up @@ -176,8 +199,10 @@ async Task WriteResponse(HttpContext context, CachedPage page)
await context.Response.Body.WriteAsync(page.Content, 0, page.Content.Length);
}

public WpResponseCacheMiddleware(RequestDelegate next, IMemoryCache cache, WpResponseCachePolicy policy, ILoggerFactory loggerFactory)
public WpResponseCacheMiddleware(RequestDelegate next, IMemoryCache cache, bool enableRazor, IHttpContextAccessor contextAccessor, WpResponseCachePolicy policy, ILoggerFactory loggerFactory)
{
_contextAccessor = contextAccessor;
_enableRazor = enableRazor;
_next = next;
_cache = cache;
_policy = policy;
Expand Down Expand Up @@ -291,6 +316,20 @@ static bool IsResponseCacheable(HttpContext context)
return true;
}

private async Task GetViewResultTask(string viewName, string page)
{
var viewResult = new ViewResult()
{
ViewName = viewName
};

var executor = _contextAccessor.HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<ViewResult>>();
var routeData = _contextAccessor.HttpContext.GetRouteData() ?? new Microsoft.AspNetCore.Routing.RouteData();
_contextAccessor.HttpContext.Items.Add("WordpressContent", page);
var actionContext = new ActionContext(_contextAccessor.HttpContext, new RouteData(), new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor());
await executor.ExecuteAsync(actionContext, viewResult);
}

public async Task Invoke(HttpContext context)
{
if (AllowCacheLookup(context))
Expand All @@ -300,7 +339,15 @@ public async Task Invoke(HttpContext context)
if (_cache.TryGetValue(key, out CachedPage page) && _policy.LastPostUpdate < page.TimeStamp)
{
_logger.LogInformation("Response served from cache.");
await WriteResponse(context, page);
if (ShouldUseRazor())
{
await GetViewResultTask("~/Pages/Wordpress.cshtml", Encoding.UTF8.GetString(page.Content));
}
else
{
await WriteResponse(context, page);
}

return;
}

Expand All @@ -320,12 +367,30 @@ public async Task Invoke(HttpContext context)

// _cache.Set(key, page, serverCacheDuration.Value, tags);
// }
if (_enableRazor)
{
if (!context.Request.Path.ToString().Contains("wp-content/") && !context.Request.Path.ToString().Contains("wp-includes/") && !context.Request.Path.ToString().Contains("wp-admin/"))
{
await GetViewResultTask("~/Pages/Wordpress.cshtml", Encoding.UTF8.GetString(page.Content));

}
}
}

return;
}
}

if (ShouldUseRazor())
{
var page = await CaptureResponse(_contextAccessor.HttpContext);
if (page != null)
{
await GetViewResultTask("~/Pages/Wordpress.cshtml", Encoding.UTF8.GetString(page.Content));
return;
}
}

// default
await _next.Invoke(context);
return;
Expand Down
2 changes: 1 addition & 1 deletion PeachPied.WordPress.AspNetCore/RequestDelegateExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ private static IApplicationBuilder InstallWordPress(this IApplicationBuilder app
plugins.Add(cachepolicy);

// app.UseMiddleware<ResponseCachingMiddleware>(cachepolicy, cachekey);
app.UseMiddleware<WpResponseCacheMiddleware>(new MemoryCache(new MemoryCacheOptions { }), cachepolicy);
app.UseMiddleware<WpResponseCacheMiddleware>(new MemoryCache(new MemoryCacheOptions { }), cachepolicy, options.EnableRazor);
}

// if (options.LegacyPluginAssemblies != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public static IServiceCollection AddWordPress(this IServiceCollection services,
throw new ArgumentNullException(nameof(services));
}

services.AddHttpContextAccessor();
//
services.AddPhp(options =>
{
Expand Down
5 changes: 5 additions & 0 deletions PeachPied.WordPress.AspNetCore/WordPressConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ public class SaltData
/// </summary>
public bool EnableResponseCaching { get; set; } = true;

/// <summary>
/// Enable embedding Wordpress into a razor view - Requires existing Pages/Wordpress.cshtml
/// Disabled by default.
/// </summary>
public bool EnableRazor { get; set; } = false;
/// <summary>
/// Overrides <c>WP_DEBUG</c> constant.
/// </summary>
Expand Down
26 changes: 26 additions & 0 deletions WordpressRazor/Pages/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@page
@model ErrorModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
32 changes: 32 additions & 0 deletions WordpressRazor/Pages/Error.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace WordpressRazor.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

private readonly ILogger<ErrorModel> _logger;

public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}

public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
10 changes: 10 additions & 0 deletions WordpressRazor/Pages/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
25 changes: 25 additions & 0 deletions WordpressRazor/Pages/Index.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace WordpressRazor.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;

public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}

public void OnGet()
{

}
}
}
8 changes: 8 additions & 0 deletions WordpressRazor/Pages/Privacy.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@page
@model PrivacyModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>
24 changes: 24 additions & 0 deletions WordpressRazor/Pages/Privacy.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace WordpressRazor.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;

public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}

public void OnGet()
{
}
}
}
53 changes: 53 additions & 0 deletions WordpressRazor/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WordpressRazor</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" href="/Index">WordpressRazor</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" href="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" href="/Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" href="/wp">Wordpress</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>

<footer class="border-top footer text-muted">
<div class="container">
&copy; 2023 - WordpressRazor - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>

<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="/js/site.js" asp-append-version="true"></script>

@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
2 changes: 2 additions & 0 deletions WordpressRazor/Pages/Shared/_ValidationScriptsPartial.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
6 changes: 6 additions & 0 deletions WordpressRazor/Pages/Wordpress.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@page "/wordpressInternal"
@using System.IO
@using Microsoft.AspNetCore.Http;
@inject IHttpContextAccessor HttpContextAccessor;

@Html.Raw(HttpContextAccessor.HttpContext.Items["WordpressContent"])
2 changes: 2 additions & 0 deletions WordpressRazor/Pages/_ViewImports.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@using WordpressRazor
@namespace WordpressRazor.Pages
3 changes: 3 additions & 0 deletions WordpressRazor/Pages/_ViewStart.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}
Loading