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 :: Blazor Cheatsheet: An Easy-to-Use Guide

clock September 1, 2025 10:12 by author Peter

Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# instead of JavaScript. It is part of the .NET ecosystem, making it possible to run C# code directly in the browser with the help of WebAssembly, or on the server with a real-time connection. This cheatsheet is a quick guide to the most critical Blazor features, syntax, and usage examples.

Blazor Hosting Models
Blazor Server

  •     Runs on the server.
  •     Uses SignalR to update UI.
  •     Small download size.

Example
@page "/counter"
<h3>Counter</h3>
<p>Count: @count</p>
<button @onclick="Increment">Click</button>

@code {
    private int count = 0;
    private void Increment() => count++;
}


Important: Faster load, but requires a constant connection.

Blazor WebAssembly

  • Runs in the browser.
  • Uses WebAssembly to execute .NET code.
  • Larger download size.
  • Important: Works offline after first load.

Components
Small building blocks of UI.
Written in .razor files.
Example
@code {
    [Parameter] public string Title { get; set; }
}

<h3>@Title</h3>

Important: Use [Parameter] for parent-to-child data.

Data Binding
1. One-way binding
<p>Hello, @name</p>
@code {
    string name = "Peter";
}


Data flows from code to UI.

2. Two-way binding

<input @bind="name" />
<p>@name</p>

@code {
    string name = "Peter";
}

Data syncs between UI and code.

Event Handling

Use @on... attributes.

Example
<button @onclick="ShowMessage">Click</button>

@code {
    void ShowMessage() => Console.WriteLine("Clicked!");
}


Lifecycle Methods

Special methods that control component behavior.

Common ones
protected override void OnInitialized() { }
protected override void OnParametersSet() { }
protected override async Task OnAfterRenderAsync(bool firstRender) { }


Important

  •     OnInitialized: Runs when the component is created.
  •     OnParametersSet: Runs when the parent sends new data.
  •     OnAfterRenderAsync: Runs after rendering UI.

Dependency Injection
Services can be injected into components.

Example
@inject HttpClient Http

<button @onclick="GetData">Fetch Data</button>

@code {
    string data;
    async Task GetData() {
        data = await Http.GetStringAsync("https://api.example.com/data");
    }
}

Important: Register services in the Program.cs file.

Routing

Define a route with @page.

Example
    @page "/about"
    <h3>About Page</h3>


For navigation
<NavLink href="/about">Go to About</NavLink>

Forms and Validation

Use EditForm with models.

Example
    @page "/form"
    <EditForm Model="user" OnValidSubmit="HandleValidSubmit">
        <InputText @bind-Value="user.Name" />
        <ValidationMessage For="@(() => user.Name)" />
        <button type="submit">Submit</button>
    </EditForm>

    @code {
        User user = new();
        void HandleValidSubmit() => Console.WriteLine("Submitted!");
        class User { public string Name { get; set; } }
    }

State Management

  •     Local state (inside component): Use fields/properties.
  •     App-wide state: Use services registered as Scoped.

JavaScript Interop

Call JS from C# or vice versa.
    Example

    @inject IJSRuntime JS

    <button @onclick="CallJS">Run JS</button>

    @code {
        async Task CallJS() {
            await JS.InvokeVoidAsync("alert", "Hello from Blazor");
        }
    }

Reusable Layouts
Use MainLayout.razor.

Example
    @inherits LayoutComponentBase
    <div class="page">
        <div class="sidebar">Menu</div>
        <div class="content">@Body</div>
    </div>

Important: @Body This is where the child page renders.

Error Handling
Use try-c
atch in methods.
    Example
    try {
        await Http.GetStringAsync("bad-url");
    } catch (Exception ex) {
        Console.WriteLine(ex.Message);
    }


Conclusion
Blazor gives developers the ability to use C# rather than JavaScript to construct cutting-edge online applications. Blazor offers the full.NET ecosystem to web development with features including components, data binding, routing, forms, dependency injection, and JavaScript interop. The most important ideas for getting started and creating scalable apps more quickly are covered in this cheat sheet.



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



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