How To Highlight Keywords Using ASP.NET Core Middleware

Today in this article we shall discuss how to highlight keywords from response using .NET core middleware. Sometime you need to search for certain keywords from a response body and then highlight them with various colours. In ASP.NET Web Forms there is an HTTP module to achieve this. In ASP.NET MVC you must have written a custom filter to achieve this task. In ASP.NET Core you can code a custom middleware to do the same. This article tells you how.

If you are not aware with ASP.NET Core middleware, I suggest you read the basics first and then continue with this.

Let’s take a scenario that closely resembles what has been mentioned above and then create a simple example to explain what we learn.

Suppose you are building a website using ASP.NET Core. The website has a search box.

You can enter some keywords to search for and press the Search key. The server side then generates the response based on the business logic and also highlights the keyword. Let’s say the keyword “Nancy” gets highlighted.

Why do you need such functionality? The above scenario is quite straight and strictly speaking doesn’t need middleware as such, just consider the following possibilities:

  • You want to automatically insert advertisements into the response depending on one or more keywords.
  • You might wish to add headers or footers dynamically.
  • You want to tamper with the response HTML to suit your needs.
  • You want to do all the above without writing any specific program in the controllers or views.

In a nutshell, you want to manipulate the response from the server to suit your needs.

Now when you understood what we want to explain, let’s create a simple middleware that really does what we wish.

Start by creating a new ASP.NET Core project based on the Web Application template. Then sumup HomeController and Index view as usual. Place the following HTML markup inside the Index view.

@{

ViewData[“Title”] = “Home Page”;

}

<div>

<form asp-action=”Index” asp-controller=”Home” method=”post”>

<input type=”text” name=”keyword” />

<input type=”submit” value=”Search” />

</form>

<p>Nancy Davolio : Her ducation comprise of a BA

in psychology from Colorado State University in 1970.

She also completed “The Art of the Cold Call.”

Nancy is a fellow of Toastmasters International.</p>

</div>

The Index view has a form tag helper that submits to the Index action of the HomeController. The method is set to POST. The form has of a textbox named keyword and a submit button. The paragraph just below the form simply holds a number of text data. The text will be generated from a database based on some server side processing. To make things simple, we won’t discuss about data access code here.

Next add a middleware class to the project and name it – MyMiddleware. The complete code of MyMiddleware is shown here:

public class MyMiddleware

{

private RequestDelegate nextMiddleware;

public MyMiddleware(RequestDelegate next)

{

this.nextMiddleware = next;

}

public async Task Invoke(HttpContext context)

{

if (context.Request.Method.ToUpper() == “POST”)

{

string highlightedText = “”;

Stream originalStream = context.Response.Body;

using (MemoryStream newStream = new MemoryStream())

{

context.Response.Body = newStream;

await this.nextMiddleware.Invoke(context);

context.Response.Body = originalStream;

newStream.Seek(0, SeekOrigin.Begin);

StreamReader reader = new StreamReader(newStream);

highlightedText = reader.ReadToEnd();

string keyword = context.Request.Form[“keyword”];

highlightedText = highlightedText.Replace

(keyword, $”<span class=’Highlight’>{keyword}</span>”);

await context.Response.WriteAsync(highlightedText);

}

}

else

{

await this.nextMiddleware.Invoke(context);

}

}

}

The MyMiddleware class has a public constructor and asynchronous Invoke() method.

The constructor gets a RequestDelegate object that is a pointer to the next middleware in the chain. The Invoke() method is responsible for invoking your custom code and then call the next middleware.

The constructor first checks if the request is POST or not. We wish to highlight a keyword later after the operation, so this check is essential. The code then develops a new MemoryStream object and sets it to the Response’s Body property. It then invokes the next middleware such that we can begin our highlight operation.

The code then reads the whole response text using a StreamReader’s ReadToEnd() method. Once we have the text, we find out the keyword entered in the textbox.Then the code substitutes that keyword from the highlightedText string variable by wrapping it in a <span> tag. The <span> tag bears the Highlight CSS class that takes care of the highlight background color and text color. Finally, the modified text is written onto the response stream using the WriteAsync() method.

The Highlight CSS class is shown below:

.Highlight

{

background-color:brown;

color:white;

font-weight:bold;

padding:4px;

}

We are done with the middleware class. Let’s design an extension method such that we can add it more easily. Add MyMiddlewareExtensions class to the project and write the following program to it:

public static class MyMiddlewareExtensions

{

public static IApplicationBuilder UseMyMiddleware

(this IApplicationBuilder app)

{

return app.UseMiddleware<MyMiddleware>();

}

}

The above code has an extension method named UseMyMiddleware() and internally calls IApplicationBuilder’s UseMiddleware<T>() method.

Now, you can finish up your middleware by invoking this extension method from the Configure() method as shown below:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseMyMiddleware();

….

….

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template:

“{controller=Home}/{action=Index}/{id?}”);

});

}

We conclude the discussion here.

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come join us with our well structured program for .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>