Back to: ASP.NET Core Tutorials For Beginners and Professionals
Blacklist and Whitelist Checks using Data Annotation in ASP.NET Core MVC
In this article, I will discuss Blacklist and Whitelist Checks using Data Annotation in ASP.NET Core MVC Applications. Please read our previous article discussing Remote Validations in ASP.NET Core MVC.
Blacklist and Whitelist Checks using Data Annotation in ASP.NET Core MVC
Both blacklisting and whitelisting are methods used to filter and validate data. Blacklisting involves blocking specific values while whitelisting permits only specific values. Let’s create custom data annotation attributes in ASP.NET Core MVC for each.
Whitelist Check using Data Annotation:
This attribute will only allow specific values from a predefined list. Let us understand this with an example. So, first, create a custom data annotation attribute with the name WhitelistAttribute.cs and then copy and paste the following code into it.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DataAnnotationsDemo.Models { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class WhiteListAttribute : ValidationAttribute { private readonly HashSet<string> _allowedValues; public WhiteListAttribute(params string[] allowedValues) { _allowedValues = new HashSet<string>(allowedValues, StringComparer.OrdinalIgnoreCase); } public override bool IsValid(object value) { if (value is string strValue) { return _allowedValues.Contains(strValue); } return false; } } }
Blacklist Check using Data Annotation:
This attribute will block specific values from a predefined list. Let us understand this with an example. So, create a custom data annotation attribute named BlackListAttribute.cs and copy and paste the following code.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DataAnnotationsDemo.Models { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class BlackListAttribute : ValidationAttribute { private readonly HashSet<string> _disallowedValues; public BlackListAttribute(params string[] disallowedValues) { _disallowedValues = new HashSet<string>(disallowedValues, StringComparer.OrdinalIgnoreCase); } public override bool IsValid(object value) { if (value is string strValue) { return !_disallowedValues.Contains(strValue); } return true; } } }
Next, create a model class where we need to apply the above WhitelistAttribute and BlackListAttribute. So, create a class file named SampleViewModel.cs and copy and paste the following code.
namespace DataAnnotationsDemo.Models { public class SampleViewModel { [WhiteList("Value1", "Value2", "Value3", ErrorMessage = "Invalid Value.")] public string FieldValue1 { get; set; } [BlackList("BadValue1", "BadValue2", "BadValue3", ErrorMessage = "This value is not allowed.")] public string FieldValue2 { get; set; } } }
Next, modify the Home Controller as follows:
using DataAnnotationsDemo.Models; using Microsoft.AspNetCore.Mvc; namespace DataAnnotationsDemo.Controllers { public class HomeController : Controller { public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(SampleViewModel sampleViewModel) { //Check if the Model State is Valid if (ModelState.IsValid) { //Save the Data into the Database //Redirect to a Different View return RedirectToAction("Successful"); } //Return to the same View and Display Model Validation error return View(sampleViewModel); } public string Successful() { return "Employee Addedd Successfully"; } } }
Next, modify the Create.cshtml view of the Home controller as follows:
@model DataAnnotationsDemo.Models.SampleViewModel @{ ViewData["Title"] = "Create"; } <div class="row"> <form asp-controller="Home" asp-action="Create" method="post" class="mt-3"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group row"> <label asp-for="FieldValue1" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="FieldValue1" class="form-control"> <span asp-validation-for="FieldValue1" class="text-danger"></span> </div> </div> <br /> <div class="form-group row"> <label asp-for="FieldValue2" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="FieldValue2" class="form-control"> <span asp-validation-for="FieldValue2" class="text-danger"></span> </div> </div> <br /> <div class="form-group row"> <div class="col-sm-10"> <button type="submit" class="btn btn-primary">Create</button> </div> </div> </form> </div>
Now, run the application and see if everything is working as expected.
Blacklist and Whitelist Character Checks using Data Annotation in ASP.NET Core MVC
If you want to create validation based on specific characters (not entire string values), you’ll have to modify our approach slightly. You will typically use regular expressions or simple string processing for character-level checks. Let’s implement both blacklist and whitelist character checks using data annotations:
Whitelist Character Check using Data Annotation:
This attribute will only allow characters from a predefined list. Modify the WhiteListAttribute class as follows:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DataAnnotationsDemo.Models { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class WhiteListAttribute : ValidationAttribute { private readonly string _allowedChars; public WhiteListAttribute(string allowedChars) { _allowedChars = allowedChars; } public override bool IsValid(object value) { if (value is string strValue) { return strValue.All(c => _allowedChars.Contains(c)); } return false; } } }
Blacklist Character Check using Data Annotation:
This attribute will block characters from a predefined list. Please modify the BlackListAttribute class as follows:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DataAnnotationsDemo.Models { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class BlackListAttribute : ValidationAttribute { private readonly string _disallowedChars; public BlackListAttribute(string disallowedChars) { _disallowedChars = disallowedChars; } public override bool IsValid(object value) { if (value is string strValue) { return !strValue.Any(c => _disallowedChars.Contains(c)); } return true; } } }
Next, modify the SampleViewModel.cs as follows:
namespace DataAnnotationsDemo.Models { public class SampleViewModel { [WhiteList("ABC123", ErrorMessage = "Only characters A, B, C, 1, 2, and 3 are allowed.")] public string Name { get; set; } [BlackList("!@#$%", ErrorMessage = "Special characters like !, @, #, $, and % are not allowed.")] public string Comment { get; set; } } }
Next, modify the Create.cshtml view as follows:
@model DataAnnotationsDemo.Models.SampleViewModel @{ ViewData["Title"] = "Create"; } <div class="row"> <form asp-controller="Home" asp-action="Create" method="post" class="mt-3"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group row"> <label asp-for="Name" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="Name" class="form-control"> <span asp-validation-for="Name" class="text-danger"></span> </div> </div> <br /> <div class="form-group row"> <label asp-for="Comment" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input asp-for="Comment" class="form-control"> <span asp-validation-for="Comment" class="text-danger"></span> </div> </div> <br /> <div class="form-group row"> <div class="col-sm-10"> <button type="submit" class="btn btn-primary">Create</button> </div> </div> </form> </div>
With the above changes, run the application and see if everything works as expected.
Real-time Examples of Blacklist and Whitelist Checks using Data Annotation in ASP.NET Core MVC
Real-time examples can help understand the practical use of blacklist and whitelist checks in real-world applications. Let’s consider two scenarios:
Username Creation in a Registration Form
For security and simplicity, we might want to:
- Whitelist: Allow only alphanumeric characters in usernames.
- Blacklist: Disallow specific offensive or reserved words from being used in the username.
Whitelist Characters:
[WhiteList("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", ErrorMessage = "Only alphanumeric characters are allowed for the username.")] public string Username { get; set; }
Blacklist Words:
[BlackList("admin", "root", "superuser", "offensiveWord1", "offensiveWord2", ErrorMessage = "This username is not allowed or contains restricted words.")] public string Username { get; set; }
Product Reviews in an E-Commerce Application
To maintain the decorum of reviews, we might want to:
- Whitelist: Ensure reviews only contain basic punctuation and alphanumeric characters.
- Blacklist: Block specific offensive words from being included in the reviews.
Whitelist Characters:
[WhiteList("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,!?() ", ErrorMessage = "Please use only letters, numbers, and basic punctuation in the review.")] public string ReviewText { get; set; }
Blacklist Words:
[BlackList("offensiveWord1", "offensiveWord2", "inappropriatePhrase1", ErrorMessage = "Please avoid using inappropriate language in the review.")] public string ReviewText { get; set; }
Note: In real-world applications, blacklists, especially for words, can be extensive. Instead of hardcoding the list, you might store it in a database or configuration file. The custom data annotation can then be modified to fetch the list from the source, ensuring it can be updated without changing the application code.
In the next article, I will discuss Displaying and Formatting Data Annotation Attributes in ASP.NET Core MVC Application. In this article, I try to explain Blacklist and Whitelist Checks using Data Annotation in ASP.NET Core MVC Application with examples. I hope you enjoy this Blacklist and Whitelist Checks using Data Annotation in the ASP.NET Core MVC article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.