European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core 9.0 Hosting - HostForLIFE :: ASP.NET Core Web API Security Using JWT Authentication

clock August 29, 2025 09:07 by author Peter

Mobile apps, SaaS platforms, IoT devices, and business systems are all powered by APIs, which form the foundation of today's digital economy.  However, a significant obstacle that comes with their popularity is security.  

APIs are one of the most popular attack vectors for cybercriminals, according to OWASP, and are frequently taken advantage of through compromised authentication, lax authorization, or data exposure. With the help of a real-world example—a bookstore API—we will walk through the entire process of securing an ASP.NET Core Web API using role-based authorization and JWT authentication in this post.

Why API Security Matters?
Imagine a bookstore API that exposes endpoints to manage books, authors, and sales. Without security:

  • Anyone could list books, update prices, or delete data.
  • Hackers could steal sensitive reports intended for admins only.
  • Attackers could flood the API with requests, causing downtime.

That’s why API security is non-negotiable.

Common API Security Threats

Before jumping into implementation, let’s recall the top threats (from OWASP API Top 10):

  1. Broken Authentication: Weak login mechanisms or missing tokens.
  2. Broken Authorization: Users accessing data or endpoints they shouldn’t.
  3. Injection Attacks (SQL, NoSQL, Command): Malicious input executed by the system.
  4. Sensitive Data Exposure: Sending unencrypted or excessive data.
  5. Rate Limiting & DoS Attacks – Flooding APIs with requests.
  6. Improper Logging & Monitoring – No visibility into attacks.

Best Practices for API Security
To mitigate these threats, adopt a defense-in-depth approach:

  • Use HTTPS everywhere—no plain HTTP.
  • Authentication & Authorization —JWT or OAuth 2.0 with RBAC/Policies.
  • Validate Inputs —prevent SQL injection and NoSQL injection.
  • Rate Limiting & Throttling —prevent abuse and DoS attacks.
  • Centralized Secret Management —Azure Key Vault or AWS Secrets Manager.
  • Error Handling —don’t leak stack traces.
  • Monitoring & Logging —track security events with Serilog or App Insights.

Implementation: Securing a Bookstore API with JWT
We’ll now build a secure Bookstore API in ASP.NET Core Web API with:

  • JWT-based authentication
  • Role-based authorization (admin vs. user)
  • Secure endpoints for books and admin reports

Step 1. Create Project
dotnet new webapi -n BookstoreApi
cd BookstoreApi


Step 2. Add NuGet Package
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 3. Configure Authentication & Authorization ( Program.cs )
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add Authentication with JWT
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "https://api.bookstore.com",
            ValidAudience = "https://api.bookstore.com"
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes("SuperSecretKey12345")) // use Key Vault in production
        };
    });

// Authorization Policies
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});

builder.Services.AddControllers();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();


Step 4. Create Auth Controller ( Controllers/AuthController.cs )
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace BookstoreApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        [HttpPost("login")]
        public IActionResult Login(string username, string password)
        {
            // Demo validation (replace with ASP.NET Identity or DB check in production)
            if (username == "admin" && password == "password")
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim(ClaimTypes.Role, "Admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey12345"));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: "https://api.bookstore.com",
                    audience: "https://api.bookstore.com",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(30),
                    signingCredentials: creds);

                return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
            }

            return Unauthorized();
        }
    }
}

Step 5. Create Secure Data Controller ( Controllers/SecureDataController.cs )
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace BookstoreApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SecureDataController : ControllerBase
    {
        // Accessible by any authenticated user
        [HttpGet("books")]
        [Authorize]
        public IActionResult GetBooks() =>
            Ok("List of available books. (Authenticated users only)");

        // Accessible only by Admin role
        [HttpGet("admin/reports")]
        [Authorize(Policy = "AdminOnly")]
        public IActionResult GetAdminReports() =>
            Ok("Sensitive sales reports. (Admins only)");
    }
}

Testing the API
Log in to get a JWT token
POST https://api.bookstore.com/api/auth/login
Body: { "username": "admin", "password": "password" }

Response
{ "token": "eyJhbGciOiJIUzI1NiIsIn..." }

Access books endpoint. (user-protected)
GET https://api.bookstore.com/api/securedata/books
Authorization: Bearer <token>


Access admin reports endpoint (admin-only)
GET https://api.bookstore.com/api/securedata/admin/reports
Authorization: Bearer <token>


Enhancing Security Further

  • Store SuperSecretKey12345 in Azure Key Vault or AWS Secrets Manager.
  • Use the AspNetCoreRateLimit NuGet package to apply rate limiting.
  • Enforce HTTPS redirection
    • app.UseHttpsRedirection();
  • Monitor API usage with Serilog and Application Insights.
  • Regularly patch dependencies and update the .NET runtime.

Conclusion
API security is not just about authentication; it’s a multi-layered defense strategy. In this article, we:

  • Reviewed the OWASP API Top 10 threats.
  • Implemented JWT authentication in ASP.NET Core.
  • Applied role-based authorization for sensitive endpoints.
  • Discussed enterprise-grade enhancements like rate limiting and secret management.

With these practices, your ASP.NET Core Web APIs will be secure, reliable, and production-ready.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Limiting ASP.NET Login by IP Address

clock August 14, 2025 08:31 by author Peter

In many web applications, especially for sensitive areas like Admin Panels, we don’t want just anyone to access the login page. Even if they have valid credentials, restricting access by IP address adds an extra layer of security. In this post, I’ll show you how to allow login only from specific IP addresses using ASP.NET C# and web.config settings.

Why Restrict Access by IP?

  • Protects sensitive admin functionality from outside networks.
  • Limits exposure to brute-force or password-guessing attacks.
  • Helps in corporate environments where admins work from known locations.

Step 1. Store Allowed IP Addresses in web.config
Open your web.config file and add this under the <configuration> section:

<configuration>
  <appSettings>
    <!-- Comma-separated allowed IP addresses -->
    <add key="AllowedIPs" value="192.168.1.10,203.0.113.25,45.67.89.10" />
  </appSettings>
</configuration>


Notes

  • Multiple IPs are separated by commas.
  • You can add or remove IPs without touching the code — just update web.config.

Step 2. Check IP Address in Code-Behind

In your login.aspx.cs or any protected page’s code-behind:
using System;
using System.Configuration;
using System.Linq;
using System.Web.UI;

public partial class Admin_Login : System.Web.UI.Page
{
    protected void Go_Click(object sender, EventArgs e)
    {
        // Step 1: Get the client's IP address
        string ipaddress = Request.UserHostAddress.ToString();

        // Step 2: Get allowed IPs from web.config
        string allowedIPs = ConfigurationManager.AppSettings["AllowedIPs"];

        // Step 3: Convert string to array and trim spaces
        string[] ipList = allowedIPs.Split(',').Select(ip => ip.Trim()).ToArray();

        // Step 4: Check if IP is in the allowed list
        if (ipList.Contains(ipaddress))
        {
            // Allowed - Continue with login process
            Response.Redirect("dashboard.aspx");
        }
        else
        {
            // Not allowed - Show alert and stop
            string script = "alert('Access Denied! Your IP is not authorized to access this page.');";
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alertScript", script, true);
        }
    }
}


How It Works?

  • Request.UserHostAddress retrieves the IP address of the user trying to log in.
  • The code reads the list of allowed IPs from web.config.
  • It splits the list into an array and trims any spaces.
  • If the user’s IP matches any of the allowed IPs → login proceeds.
  • If not → a JavaScript alert displays "Access Denied!" and stops the process.

Important Tips

  • When testing locally, you might see 127.0.0.1 (IPv4) or ::1 (IPv6 loopback address).
  • That’s normal for localhost — to test real IP restrictions, deploy to a server, or access from another device.
  • For cloud hosting (Azure, AWS, etc.), sometimes you’ll need to check headers, like "HTTP_X_FORWARDED_FOR" for the real client IP.
  • Keep the web.config secure, never expose it publicly.

Conclusion
Restricting access by IP address is a simple yet effective security enhancement for admin login pages in ASP.NET. By keeping the allowed IP list in web.config, you can manage access without redeploying your application.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: The Best Way to Simplify Your.NET Project

clock August 11, 2025 08:04 by author Peter

This post will show you the best practices for cleaning up your.NET project. Please read my previous post on best practices for cleaning up your.NET Core project before we begin.

Let's get started. The clean project principles are mostly the same, but in .NET Framework there are some differences in structure, DI, and configuration because:

  • There's no Program.cs with minimal hosting model.
  • You often work with ASP.NET MVC 5, Web API 2, or WCF instead of ASP.NET Core.
  • Dependency Injection and configuration are not built-in — you use NuGet packages (e.g., Autofac, Unity, Ninject).

Here’s the .NET Framework–specific best practices:

1. Keep a Layered Architecture

Example for ASP.NET MVC 5 / Web API 2:

MyApp.sln
 ├─ MyApp.Web         // MVC or Web API project (Controllers, Views)
 ├─ MyApp.Application // Service layer (business logic, DTOs)
 ├─ MyApp.Domain      // Entities, enums, interfaces
 ├─ MyApp.Infrastructure // EF6, repositories, external integrations
 └─ MyApp.Tests       // Unit & integration tests


Note: You can still do feature-based folders inside Web or Application.

2. Use Dependency Injection (Manually Registered)

In .NET Framework, you add a DI container manually, for example Autofac:
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<OrderService>().As<IOrderService>();
builder.RegisterType<OrderRepository>().As<IOrderRepository>();

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));


Note: Do this in Global.asax → Application_Start().

3. Keep Controllers Thin

Same as in Core: controllers only handle HTTP flow — move logic into services.

4. Use ViewModels & DTOs

Avoid passing EF entities directly to views or API responses.
Use AutoMapper for mapping between domain models and DTOs:
Mapper.Initialize(cfg => cfg.CreateMap<Order, OrderDto>());

5. Centralize Exception Handling
In MVC/Web API, use:
Global Filters:
public class GlobalExceptionFilter : IExceptionFilter {
    public void OnException(ExceptionContext filterContext) {
        // log error
        filterContext.Result = new ViewResult { ViewName = "Error" };
        filterContext.ExceptionHandled = true;
    }
}


Register in FilterConfig.cs
6. Keep Configuration Out of Code
Use Web.config for settings.
For strongly typed configs:
var settingValue = ConfigurationManager.AppSettings["MySetting"];

Or use Settings.settings file for auto-generated config classes.

7. Avoid Magic Strings / Numbers
Same principle:
public static class Roles {
    public const string Admin = "Admin";
}

8. Apply SOLID
Even in .NET Framework — especially important because older projects tend to get “God classes”.

9. Use Filters & Action Attributes

Instead of putting auth/logging/validation code in controllers:

  • AuthorizationFilterAttribute for role-based checks.
  • ActionFilterAttribute for logging and pre/post action hooks.

10. Use EF6 Best Practices

  • Avoid lazy loading unless needed.
  • Use AsNoTracking() for queries that don’t need entity tracking.
  • Keep DB logic in repositories or a dedicated DAL.

11. Unit Testing Without Core’s Built-in DI
Mock services using Moq/FakeItEasy.
Avoid static dependencies — make them injectable.

12. Keep Global.asax Clean

  • Move route configs to RouteConfig.cs.
  • Bundle/minify in BundleConfig.cs.
  • Register filters in FilterConfig.cs.
  • Only call setup methods in Application_Start().


13. Static Analysis & Style Rules
Use FxCop, StyleCop, or ReSharper for code quality.

14. Async in ASP.NET

Use async/await in MVC/Web API to free threads for scalability.

public async Task<ActionResult> GetOrders() {
    var orders = await _orderService.GetOrdersAsync();
    return Json(orders, JsonRequestBehavior.AllowGet);
}


15. Document Your APIs
For Web API 2, use Swashbuckle for .NET Framework to generate Swagger docs.

Conclusion
Here we tried to cover Best practice to make your project cleaner in .NET



European ASP.NET Core 9.0 Hosting - HostForLIFE :: How Can a.NET Web API (JWT, OAuth, Identity) be Secured?

clock August 8, 2025 08:03 by author Peter

Why Is It Important to Secure Your Web API?
APIs are frequently the foundation of contemporary applications, particularly in cloud-based and microservice architectures. Your API is susceptible to attacks including impersonation, illegal access, and data leaks if it is left unprotected. This is where ASP.NET Core Identity, OAuth 2.0, and JWT (JSON Web Tokens) come in handy, offering a comprehensive toolkit for securely authorizing and authenticating users.

Overview of Key Security Concepts

Term What It Means

Authentication

Verifying who the user is (e.g., login)

Authorization

Controlling what the user can do (e.g., access certain endpoints)

JWT

A secure, compact token used to carry claims about the user

OAuth 2.0

An open standard for delegated authorization

ASP.NET Core Identity

Framework for managing users, roles, and credentials

1. JWT Authentication in ASP.NET Core Web API
JWT (JSON Web Token) is the most common way to secure APIs in a stateless way.

Step-by-Step: Add JWT Authentication
Step 1. Add Required NuGet Packages.
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 2. Configure JWT Authentication in Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "yourapp.com",
            ValidAudience = "yourapp.com",
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes("super_secret_key_12345"))
        };
    });

builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

Step 3. Secure Your Endpoints
[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
    return Ok("You are authorized!");
}


Step 4. Issue a JWT Token on Login
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
    // Dummy check
    if (login.Username == "admin" && login.Password == "password")
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, login.Username)
        };
        var key = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes("super_secret_key_12345"));

        var creds = new SigningCredentials(
            key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: "yourapp.com",
            audience: "yourapp.com",
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds);

        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token)
        });
    }
    return Unauthorized();
}


2. OAuth 2.0 Authorization
OAuth 2.0 is an authorization framework used to grant access to third-party apps without sharing passwords. It’s used widely in login with Google, Facebook, Microsoft, etc.

Common OAuth Scenarios

  • Sign in users via Google/Facebook.
  • Authorize access to external services (like GitHub API).
  • Delegate API access using access tokens.

Add OAuth2 to Your Web API
Example: Add Google Authentication.
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
)
.AddCookie()
.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
{
    options.ClientId = "your-google-client-id";
    options.ClientSecret = "your-google-client-secret";
});


3. ASP.NET Core Identity
ASP.NET Core Identity is a full user management system that supports:

  • Registration
  • Login/Logout
  • Password management
  • Role-based authorization

Install Identity
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

Configure Identity in Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

Secure an Endpoint with Role
[Authorize(Roles = "Admin")]
[HttpGet("admin-only")]
public IActionResult GetAdminData()
{
    return Ok("You are an Admin!");
}

Combine Identity + JWT for Token-Based User Management
You can extend Identity to generate JWT tokens after login instead of using cookies.

Example: Identity Login Returning JWT

[HttpPost("token")]
public async Task<IActionResult> Token([FromBody] LoginModel model)
{
    var user = await userManager.FindByNameAsync(model.Username);
    if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("your_super_secret_key");

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, user.UserName),
            }),
            Expires = DateTime.UtcNow.AddHours(1),
            SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return Ok(new { token = tokenHandler.WriteToken(token) });
    }
    return Unauthorized();
}

Extra Security Best Practices

Best Practice Why It Matters
Use HTTPS Encrypts traffic between client and server
Hash & salt passwords Prevents password leaks if DB is compromised
Set token expiration Reduces the risk of stolen tokens
Rotate keys regularly Improves security hygiene
Use claims & roles properly Enforces fine-grained authorization
Logout (Token revocation) Invalidate sessions when needed

Summary

Feature Use When...
JWT You need stateless, fast, token-based auth
OAuth2 You allow third-party logins or services
Identity You manage your user accounts and roles

Conclusion

It is imperative that your.NET Web API be secured. The secret is to carefully integrate them according to the requirements of your application, whether you choose to utilize ASP.NET Core Identity for user management, OAuth2 for third-party authorization, or JWT for stateless APIs.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Utilizing a Secure API to Verify UPI IDs

clock August 4, 2025 07:55 by author Peter

To guarantee accuracy and lower failure rates in digital payment systems, a UPI (Unified Payments Interface) ID must be validated before a transaction is started. Without revealing any critical implementation details, this article describes how to integrate a UPI ID validation API using JavaScript and C# (ASP.NET). To demonstrate, we'll use a fictitious endpoint.

Why Validate UPI IDs?

  • Avoid transaction failures due to incorrect UPI IDs
  • Improve user experience by providing real-time feedback
  • Ensure the UPI ID belongs to the correct customer

Technologies Used

  • C# (ASP.NET WebForms/Backend)
  • JavaScript (AJAX for frontend calls)
  • JSON for data communication
  • Dummy API endpoint (replace with actual provider)

Example API Request
POST https://dummyapi.example.com/v1/payments/validate/vpa
Content-Type: application/json
{
    "vpa": "user123@dummyupi"
}


Successful Response
{
  "vpa": "user123@dummyupi",
  "customer_name": "John Doe",
  "success": true
}

Invalid UPI Response
{
  "error": {
    "code": "BAD_REQUEST_ERROR",
    "description": "Invalid VPA. Please enter a valid Virtual Payment Address",
    "source": "customer",
    "step": "payment_initiation",
    "reason": "invalid_vpa"
  }
}

Backend Implementation (C#)
Here’s a simplified C# function to validate a UPI ID via HTTP POST.
public static string ValidateUPIID(string upi)
{
    string responseJson = "";
    try
    {
        var requestObj = new { vpa = upi };
        string requestJson = new JavaScriptSerializer().Serialize(requestObj);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://dummyapi.example.com/v1/payments/validate/vpa");
        request.Method = "POST";
        request.ContentType = "application/json";

        byte[] data = Encoding.UTF8.GetBytes(requestJson);
        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            responseJson = reader.ReadToEnd();
        }

        if (responseJson.Contains("success"))
        {
            var jsonObj = new JavaScriptSerializer().Deserialize<UPIResponse>(responseJson);
            return jsonObj.success ? $"success - {jsonObj.customer_name}" : "failed - ";
        }
        else if (responseJson.Contains("error"))
        {
            var errorObj = new JavaScriptSerializer().Deserialize<UPIErrorResponse>(responseJson);
            string errDesc = !string.IsNullOrEmpty(errorObj.error.description) ? errorObj.error.description : "Invalid VPA";
            string errReason = !string.IsNullOrEmpty(errorObj.error.reason) ? errorObj.error.reason : "invalid_vpa";
            return $"reason - {errDesc} - {errReason}";
        }

        return "failed - unknown error";
    }
    catch (Exception ex)
    {
        return "error - " + ex.Message;
    }
}

public class UPIResponse
{
    public string vpa { get; set; }
    public string customer_name { get; set; }
    public bool success { get; set; }
}
public class UPIErrorResponse
{
    public UPIError error { get; set; }
}
public class UPIError
{
    public string code { get; set; }
    public string description { get; set; }
    public string source { get; set; }
    public string step { get; set; }
    public string reason { get; set; }
}

JavaScript Frontend (AJAX Call)
<div class="bid-content-common bid-content-3">
    <label class="upiid-lble">UPI ID</label>
    <input id="txtupiid" runat="server" type="text" placeholder="Enter the UPI ID"
           onchange="UPIIDtxtboxchanges()" onblur="handleBlur()" />
    <span id="upidtxt"></span>
    <input id="upidvalidation" type="hidden" />
    <button id="applybtn">Apply</button>
</div>

<script>
    function UPIIDtxtboxchanges() {
        var applybtn = document.getElementById("applybtn");
        var upitxt = document.getElementById("upidvalidation");
        var txtbutton = document.getElementById("txtupiid");
        var verifytxt = document.getElementById("upidtxt");

        upitxt.value = 'Verify';
        upitxt.style.backgroundColor = "#F0F0F0";
        upitxt.style.border = "2px solid #979F6E";
        upitxt.style.color = "black";
        verifytxt.innerText = "";
        applybtn.style.pointerEvents = "auto";
    }

    function handleBlur() {
        // Assuming upivalidationmethod takes a callback function
        upivalidationmethod(function (isValid) {
            if (isValid) {
                return true;
            } else {
                return false;
            }
        });
    }

    function upivalidationmethod(callback) {
        var upiId = document.getElementById("upiInput").value;

        $.ajax({
            type: "POST",
            url: "/your-page.aspx/ValidateUPI",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ upi: upiId }),
            success: function (res) {
                var status = res.d.split('-');
                if (status[0] === "success") {
                    $("#message").text("Valid UPI: " + status[1]).css("color", "green");
                    callback(true);
                } else {
                    $("#message").text("Invalid UPI").css("color", "red");
                    callback(false);
                }
            },
            error: function () {
                $("#message").text("Error validating UPI").css("color", "red");
                callback(false);
            }
        });
    }
</script>


Best Practices

  • Always encrypt sensitive credentials used in API headers.
  • Validate and sanitize inputs to avoid injection or malformed requests.
  • Log and monitor UPI validation failures for system analysis.

Conclusion
Integrating a UPI ID validation step into your application ensures smoother payments, fewer failed transactions, and a better user experience. Using an API for this process helps streamline validation with real-time customer name checks and error handling. Replace the dummy API URL and credentials with your actual provider’s details securely in production.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: New Features in.NET 10: Quantum Security & JSON Updates

clock July 21, 2025 09:05 by author Peter

The .NET libraries have seen significant enhancements with Microsoft's.NET 10 Preview 6 release, which focuses on security, accuracy, and cryptographic innovation. The capabilities in this preview add more control and future-proof security options to your development toolbox, whether you're working with JSON data interchange or investigating sophisticated cryptographic techniques.

In this article, we’ll dive into the key updates in Preview 6.

  • Disallowing duplicate JSON properties
  • Enforcing strict JSON serialization
  • Introduction of Post-Quantum Cryptography (PQC) support

Option to Disallow Duplicate JSON Properties
Duplicate JSON keys have historically been a gray area in JSON parsers. The JSON specification doesn’t mandate a standard behavior for duplicate properties, which can result in unpredictable runtime behavior and even security vulnerabilities.

Why does it matter?
In scenarios where malicious users could manipulate JSON payloads, duplicate properties could be used to override expected values, posing a serious security risk.

New Feature
The new AllowDuplicateProperties flag in JsonSerializerOptions and JsonDocumentOptions can now be set to false, ensuring that duplicate properties throw exceptions, improving both security and consistency.

Example
string json = """{ "Value": 1, "Value": -1 }""";
Console.WriteLine(JsonSerializer.Deserialize<MyRecord>(json).Value); // Output: -1 (last one wins)
// Enabling strict duplicate checks
JsonSerializerOptions options = new() { AllowDuplicateProperties = false };
// These will now throw JsonException
JsonSerializer.Deserialize<MyRecord>(json, options);
JsonSerializer.Deserialize<JsonObject>(json, options);
JsonSerializer.Deserialize<Dictionary<string, int>>(json, options);
JsonDocumentOptions docOptions = new() { AllowDuplicateProperties = false };
JsonDocument.Parse(json, docOptions); // Throws JsonException
record MyRecord(int Value);


Strict JSON Serialization Options
By default, the JSON serializer in .NET is designed to be flexible, but sometimes too flexible for high-security or precision-critical applications.
Introducing JsonSerializerOptions.Strict

A new strict preset configuration enables best practices automatically, including.

  • Disallowing unmapped members
  • Disabling duplicate properties
  • Enforcing case-sensitive property matching
  • Respecting nullable annotations and required constructor parameters

This preset helps enforce strict contracts between your models and incoming JSON.

Use Case Example
string validJson = """{ "Name": "Alice", "Age": 30 }""";
var person = JsonSerializer.Deserialize<Person>(validJson, strictOptions);

record Person(string Name, int Age);

Use this when deserialization must exactly match your schema, with no surprises.

Post-Quantum Cryptography (PQC)
As the threat of quantum computing becomes more real, cryptographic standards are evolving. Microsoft is proactively addressing this with Post-Quantum Cryptography (PQC) support.

With .NET 10 Preview 6, support for PQC is being introduced through the Windows CNG (Cryptography Next Generation) platform. This enables the use of quantum-resistant algorithms in your .NET applications.

Sample: Verifying a PQC Digital Signature
using System;
using System.IO;
using System.Security.Cryptography;

private static bool ValidateMLDsaSignature(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature,

string publicKeyPath)
{
    string publicKeyPem = File.ReadAllText(publicKeyPath);
    using (MLDsa key = MLDsa.ImportFromPem(publicKeyPem))
    {
        return key.VerifyData(data, signature);
    }
}


Note. This works on Windows Insider builds with PQC support (Canary Channel).
Microsoft is also working on down-level support for the .NET Framework via the Microsoft.Bcl.Cryptography package, helping legacy apps move toward quantum-safe cryptography.

Conclusion

.NET 10 Preview 6 is more than just an incremental update, it is laying the foundation for secure, resilient, and precise applications. From safer JSON parsing to next-generation cryptographic capabilities, this release reflects Microsoft’s focus on developer security and interoperability.

Try It Out

You can start testing these features today using the .NET 10 Preview 6 SDK. If you’re a library author, security-focused developer, or someone handling sensitive data contracts, these updates are for you.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Examples to Help You Understand Dependency Injection (DI) in.NET Core

clock July 15, 2025 10:08 by author Peter

Dependency Injection (DI): What is it?
A design pattern called Dependency Injection (DI) is used to accomplish loose coupling between classes and their dependencies. Dependencies are injected from the outside, typically by a framework like.NET Core, rather than being created by a class itself. This encourages improved modularity, testability, and maintainability in application design.

Why Use DI?
Improves testability (easily mock dependencies)
Enhances flexibility and maintainability

Supports SOLID principles, especially:

  • Inversion of Control (IoC)
  • Single Responsibility Principle

How DI Works in .NET Core?
.NET Core comes with a built-in IoC container that supports three main service lifetimes:

Lifetime Description Example Use Case
Singleton One instance for the entire application Caching, config, loggers
Scoped One instance per HTTP request User/session-level services
Transient New instance every time it's requested Lightweight, stateless logic

Step-by-Step Example: Injecting a Service
1. Define an Interface

public interface IMessageService
{
    string GetMessage();
}


2. Create a Concrete Implementation
public class HelloMessageService : IMessageService
{
    public string GetMessage()
    {
        return "Hello from DI!";
    }
}


3. Register the Service in the Program.cs (.NET 6+)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IMessageService, HelloMessageService>(); // DI registration


4. Inject the Service in a Controller
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    private readonly IMessageService _messageService;

    public HomeController(IMessageService messageService)
    {
        _messageService = messageService;
    }

    [HttpGet]
    public string Get() => _messageService.GetMessage();
}


Output
GET /home
=> "Hello from DI!"
Real-World Use Case

In a recent project, we used DI to inject:

  • ILoggingService
  • IEmailService
  • IUserRepository

This allowed us to easily swap implementations during unit testing and to mock external services such as SendGrid and SQL Server, enabling a much more testable and scalable architecture.

Summary

  • DI is built into .NET Core via IServiceCollection.
  • Encourages clean, testable, and modular code.
  • Supports different service lifetimes (Singleton, Scoped, Transient).
  • Use constructor injection as the standard approach.


European ASP.NET Core 9.0 Hosting - HostForLIFE :: Microsoft Entra External ID Integration with Blazor Web Application

clock July 11, 2025 08:58 by author Peter

Managing external user IDs becomes crucial as businesses provide more digital services to clients, partners, and outside developers. By offering a standards-based, scalable, and safe identification solution that works well with contemporary apps, Microsoft Entra External ID assists in overcoming this difficulty. 

 This article will demonstrate how to combine an ASP.NET Core MVC application with Microsoft Entra External ID. Setting up authentication, managing user claims, and enforcing authorization for external users will all be covered. This article will assist you in implementing identity management, whether you're creating a secure, user-friendly application or a multi-tenant SaaS platform.

Get started with Integration
Step 1. Open Visual Studio 2022, click on Create a New Project, select ASP.NET Core Web App (MVC) Template, provide a project name, and click Next to get a wizard below.

Step 2. In the service dependencies wizard, add the dotnet misidentify tool to add a Microsoft identity platform, and click Next

Step 3. Select the tenant and click Create New to register a new External Entra ID application or select an existing application,  as shown in the figure below.

Step 4. The next step is to add Microsoft Graph or any other API. For a demo, I'm just going to skip this process.
Finally, click next; it will scaffold all required NuGet packages and changes in the Program.cs, appsettings.json

Step 5. In this step, switch to entra.microsoft.com and ensure you are in the External ID tenant, go to the user flow. Please refer to my article to check how to create a user flow. Select the user flow and click on Application to link our application to the user flow, as shown in the figures below.


Step 6. Finally, run the application. It will display the Microsoft Entra External ID user flow sign-in screen. Sign in using your social account credentials. After successful authentication, the application will navigate to the Home screen.

Summary
A detailed tutorial on how to integrate Microsoft Entra External ID with an ASP.NET Core MVC application has been shown to us. It clarifies key ideas including maintaining user claims, implementing secure access controls, and configuring authentication for external users. Developers may improve application security and offer a smooth experience for external partners, clients, and vendors by leveraging Microsoft's identity platform. The manual supports identity management's strategic strategy as well as its technical implementation.



European ASP.NET Core 9.0 Hosting - HostForLIFE :: LINQ and Data View in C# and VB.NET

clock July 8, 2025 07:29 by author Peter

Here, a base class example and an exploration of Data View and LINQ (Language-Integrated Query) using DataTable Query for retrieving unique values from the database will be provided. LINQ is compatible with the most recent version,.NET 9, as well as.NET Core 3.1,.NET 5, and.NET 6. We will retrieve the data from a DataTable to a DataView using an example of a Book Class. Below is an example of a model-based class.

Book.cs
public class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

Book Class Output Example without using LINQ.

BookID Title Author Genre Price
1 XXX xxx 1.1 45.00
2 YYY yyy 2.1 45.00
3 ZZZZ zzz 1.1 50.00
4 AAA aaa 1.1 30.00

To retrieve the unique values of the version sorted by price value, the example code below is provided for C# and VB.NET.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Book> books = new List<Book>
        {
            new Book { BookID = 1, Title = "XXX", Author = "xxx", version = "1.1", Price = 45.00m },
            new Book { BookID = 2, Title = "YYY", Author = "yyy", version = "2.1", Price = 50.00m },
            new Book { BookID = 3, Title = "ZZZZ Hobbit", Author = "zz", version = "1.1", Price = 30.00m },
            new Book { BookID = 4, Title = "AAA", Author = "aa", version = "1.1", Price = 42.00m }
        };

        // LINQ: Get all 1.1 books sorted by price
        var programmingBooks = books
            .Where(b => b.version == "1.1")
            .OrderBy(b => b.Price);

        Console.WriteLine("Books (sorted by price):");
        foreach (var book in programmingBooks)
        {
            Console.WriteLine($"{book.Title} by {book.Author} - ${book.Price}");
        }
    }
}

class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string version { get; set; }
    public decimal Price { get; set; }
}

Dim bookTable As New DataTable()
bookTable.Columns.Add("BookID", GetType(Integer))
bookTable.Columns.Add("Title", GetType(String))
bookTable.Columns.Add("Author", GetType(String))
bookTable.Columns.Add("Genre", GetType(String))
bookTable.Columns.Add("Price", GetType(Decimal))

' Sample data
bookTable.Rows.Add(1, "XXX", "xxx", "1.1", 45.0D)
bookTable.Rows.Add(2, "YYY", "yyy", "1.2", 45.0D)
bookTable.Rows.Add(3, "ZZZ", "zzz", "2.1", 50.0D)
bookTable.Rows.Add(4, "AAA", "aa", "1.1", 30.0D)

Dim view As New DataView(bookTable)
Dim distinctBooks As DataTable = view.ToTable(True, "Title", "Author")

For Each row As DataRow In distinctBooks.Rows
    Console.WriteLine($"Title: {row("Title")}, Author: {row("Author")}")
Next

Output
Title: XXX, Author: xxx
Title: ZZZZ, Author: zz
Title: AAA, Author: aa



European ASP.NET Core 9.0 Hosting - HostForLIFE :: Base Class Library (BCL) for .NET

clock June 30, 2025 09:58 by author Peter

One crucial component of the.NET framework is the Base Class Library (BCL). Microsoft provides a basic collection of pre-built classes and types for the.NET platform called the Base Class Library (BCL). These are the fundamental components of nearly all.NET applications, be they desktop, online, console, or API projects. It is closely linked with the Common Language and is a component of the Framework Class Library (FCL). It functions similarly to the standard toolkit included with the.NET runtime, prepared to tackle common programming tasks such as:

  • Working with strings, numbers, and dates
  • Reading and writing files
  • Managing collections of data
  • Performing network operations
  • Handling threads and asynchronous tasks
  • Encrypting and securing data
  • Parsing XML and JSON
  • Reflecting on types and assemblies

It’s implemented in assemblies like System.Runtime.dll, System.Private.CoreLib.dll, and others, and is shared across all .NET implementations—whether you're building with .NET Core, .NET Framework, or modern .NET (6/7/8).

Think of the BCL as the foundation toolkit that every .NET developer uses — just like a workshop full of power tools and templates to build robust applications without reinventing the wheel.

Framework Class Library (FCL)
The Framework Class Library includes the BCL but also adds broader APIs for developing web apps (ASP.NET), desktop apps (WinForms/WPF), database access (ADO.NET), and more.

Common Language Runtime (CLR)
The CLR is the execution engine of .NET. It handles memory management, type safety, garbage collection, exception handling, and security.

In my opinion as a developer, we use many components from the Base Class Library in our day-to-day projects. We often see some libraries being used more commonly than others. It's helpful to understand what they are and how they work with real examples.

We build our house (Application) on a strong foundation (CLR), construct it using tools like List<T>, File, and Console (BCL), and then decorate it with features like ASP.NET, ADO.NET, and WinForms (FCL).

Why Use Base Class Library (BCL) in .NET?

  • Saves Development Time - No need to write common functionality from scratch. Built-in classes like List<T>, File, DateTime make tasks faster and easier.
  • Reduces Bugs - Microsoft’s BCL classes are thoroughly tested and reliable. Reduces the risk of writing error-prone custom implementations.
  • Increases Productivity - Developers can focus on business logic instead of low-level utilities. Example: File.ReadAllText("file.txt") reads an entire file in one line.
  • 4Cross-Platform Compatible - Works consistently across Windows, Linux, and macOS using .NET Core / .NET 5+. Ensures platform-independent development.
  • Improves Code Readability - Standardized APIs make code easier to read, understand, and maintain. Using familiar classes like StringBuilder, Dictionary, and Console helps teamwork.
  • Boosts Performance - Many BCL classes (like Stopwatch, Span<T>) are optimized for speed and memory.Useful for performance-critical tasks.
  • Consistent Design - All .NET languages (C#, VB.NET, F#) use the same BCL. APIs follow predictable naming and behavior patterns.


Commonly Used Base Class Libraries
1. System

System is the core namespace in the .NET Base Class Library (BCL). It contains the fundamental types and classes that almost every .NET application uses — including data types, console I/O, math functions, exceptions, and more. The foundation layer of all your C# programs — like the basic bricks and cement used in every building project. It includes essential types like:

  • Primitive types: System.Int32, System.Boolean, System.String, etc.
  • Base object model: System.Object, System.Type, System.Exception
  • Utilities: System.Math, System.Convert, System.Environment
  • Date and time: System.DateTime, System.TimeSpan
  • Console I/O: System.Console
  • Nullable types: System.Nullable<T>
  • Tuples and value types: System.ValueTuple, System.Enum

Example code:
using System;

class Program
{
    static void Main()
    {
        string name = "C# Community";
        int year = DateTime.Now.Year;

        Console.WriteLine($"Hello, {name}! Welcome to the year {year}.");
    }
}


We used:
    System.String
    System.DateTime
    System.Console


All from the System namespace—no extra libraries needed.

Why Is It Important?

It’s automatically referenced in most .NET projects, It provides the building blocks for all other namespaces and It’s the default namespace for many language features (e.g., int is an alias for System.Int32).

2.  System.IO
The System.IO namespace in .NET is we go-to toolkit for handling files, directories, and data streams. It’s part of the Base Class Library (BCL) and provides everything we need to read, write, and manage data on disk or in memory. It enables to:

  • Read and write files (File, FileStream, StreamReader, StreamWriter)
  • Work with directories (Directory, DirectoryInfo)
  • Handle paths (Path)
  • Monitor file system changes (FileSystemWatcher)
  • Read/write binary data (BinaryReader, BinaryWriter)
  • Use memory streams (MemoryStream)


Example Code
using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string path = "myFile.txt";
        File.WriteAllText(path, "Hi! C# community, I am Miche!");
        string content = File.ReadAllText(path);
        Console.WriteLine("File content:\n" + content);
    }
}


We used using System; and using System.IO;

These two using statements import the namespaces required.
System: Gives access to Console, String, etc.
System.IO: Gives access to file-related classes like File.


Common Classes in System.IO

Class Purpose
File / FileInfo Create, delete, copy, move files
Directory / DirectoryInfo Manage folders
StreamReader / StreamWriter Read/write text
BinaryReader / BinaryWriter Read/write binary data
FileStream Low-level file access
Path Manipulate file paths
MemoryStream Work with data in memory
FileSystemWatcher Watch for file changes (great for logging or syncing apps)

Why Is It Important?
To save data locally (like logs, configs, user input),  To read config files or resources in your application, To upload/download files in web apps and To interact with the file system in background jobs, APIs, or desktop tools. System and System.IO are libraries commonly used by developers from beginner to advanced levels. In this article, we introduced them briefly, and in the upcoming articles, we will explore other important libraries — explaining them in simple terms, along with detailed examples.

Essential .NET Base Class Libraries (BCL)

Namespace What It Is  Why It’s Important Use Case / Class
System Core types and base functionality Fundamental types used in all .NET code Console, String, DateTime, Math
System.IO File and stream handling Enables file read/write, stream data File, FileInfo, StreamReader, Path
System.Net.Http HTTP communication Connects to REST APIs or web servers HttpClient for GET/POST requests
System.Collections.Generic Generic data collections Manage dynamic data with type safety List<T>, Dictionary<K,V>
System.Linq LINQ querying over collections Simplifies filtering, sorting, and projections Where, Select, FirstOrDefault
System.Threading.Tasks Asynchronous programming Perform non-blocking background operations Task, async/await, Task.Run()
System.Text Text processing and manipulation Efficient string handling and encoding StringBuilder, Encoding.UTF8
System.Text.RegularExpressions Regex-based pattern matching Validate input, extract data from text Regex.IsMatch, Regex.Replace
System.Globalization Culture-aware formatting Supports localization for global users CultureInfo, DateTime.ToString("D", culture)
System.Diagnostics Logging, tracing, performance Debug, benchmark, trace app behavior Stopwatch, Debug.WriteLine()
System.Reflection Runtime type inspection Enables plugins, dependency injection, metadata access Type, Assembly, PropertyInfo
System.Security.Cryptography Cryptographic services Secure hashing, encryption, certificates SHA256, Aes, RNGCryptoServiceProvider
System.ComponentModel Metadata for components Data annotations, property binding INotifyPropertyChanged, attributes
System.Timers Timer-based scheduling Execute code at intervals Timer.Elapsed, auto-repeating logic
System.Configuration App config settings access Read/write app configuration files ConfigurationManager.AppSettings[]
System.Data Core data access tools Work with databases or tabular data DataTable, DataSet, DbConnection

How to Use Base Class Library (BCL) in .NET

  • BCL is built-in: No need to install — it comes with .NET automatically.
  • Use using statements: Add namespaces like System, System.IO, System.Collections.Generic at the top of your file.
  • Call built-in classes: Use BCL types like Console, DateTime, File, List<T>, etc.
  • Works in all project types: Console apps, web apps, APIs, desktop apps, etc.
  • Saves time: Gives you ready-to-use tools for common tasks like reading files, formatting dates, or handling collections.

Conclusion
The BCL is more than just a library—it’s the beating heart of .NET development. Mastering these foundational namespaces allows us to build clean, efficient, and maintainable software across a wide range of applications. From System.Net.Http for HTTP communication to System.Text.Json for serialization, these tools empower us to write less boilerplate and focus more on business logic.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in