Extract Fragment Middleware
What It Is
Middleware to extract an element from rendered HTML and return itStatus
Just a POC. I wrote it for an Opti sales process. It never saw production, though it’s running on this site right now (see below).
Details
This is a middleware module for a .NET Core web app that allows you to specify a CSS selector in the querystring.
domain.com/path/to/whatever?extract=div.main
The module will extract and return just that HTML from the response (div.main
in the example). Your app will render the entire page, but then just “pluck out” the HTML you want and get rid of the rest.
If there’s more than one matching tag, it will find them all then concatenate them.
It defaults to the outer HTML, but you can pass in a scope
argument of inner
if you just want the contents. (That’s all scope
does right now. The only other thing I thought of is maybe attribute
… but why?)
This middleware essentially turns your web app into an “HTML fragment server,” which is handy for HTML-as-a-Service situations, like with HTMX.
It’s running on this website for no particular reason. Here are some examples (note the URLs – feel free to use those querystrings on any page on this site):
See the contents of the MAIN element of this page
See the contents of the TITLE element of this page (note that this has scope=inner
, because without that, you’d get the surrounding TITLE
tags as well, which do not render by default, so you would see nothing)
(Note that without any of the surrounding HTML, it doesn’t load styles or meta, which includes the encoding…)
Add it like this, in Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ExtractFragmentMiddleware>();
}