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

ASP.NET Core 10.0 Hosting - HostForLIFE.eu :: A Comprehensive Guide to API Security for ASP.NET Core

clock May 22, 2026 07:23 by author Peter

One of the most crucial aspects of contemporary software development is API security. Attackers may steal data, gain access to private information, alter systems, or even cause your program to fail if your API is not secure. This post will teach us several security measures for the ASP.NET Core Web API with clear explanations, practical examples, and sophisticated methods.

What is API Security?
API Security means protecting your API from:

  • Unauthorized access
  • Data theft
  • SQL Injection
  • Cross-site attacks
  • Brute-force attacks
  • Token hijacking
  • Server misuse
  • Fake requests
  • DDoS attacks

Why API Security is Important?
Without security:

  • Hackers can access private data
  • Anyone can call your APIs
  • Database can be hacked
  • Users’ passwords can leak
  • System performance can be destroyed

Example:
Imagine your banking API has no authentication.

Anyone can call:
GET /api/account/balance?id=1

Then all customer data becomes public.

Security Levels in ASP.NET Core API

LevelSecurity Type

Beginner

HTTPS, Authentication

Intermediate

JWT, API Keys, Validation

Advanced

Rate Limiting, IP Whitelisting

Enterprise

OAuth2, Zero Trust, WAF

1. HTTPS Security (Basic Level)

HTTPS encrypts data between client and server.

Without HTTPS:

  • Data travels as plain text.

With HTTPS:

  • Data becomes encrypted.

Enable HTTPS in ASP.NET Core
In Program.cs:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpsRedirection(options =>
{
    options.HttpsPort = 443;
});

var app = builder.Build();

app.UseHttpsRedirection();

app.Run();

2. Authentication Security
Authentication checks:
“Who are you?”

Example:

  • Username + Password
  • WT Token
  • OAuth Login

3. Authorization Security
Authorization checks:
“What are you allowed to access?”

Example:

  • Admin can delete users
  • User can only view profile

4. JWT Token Authentication
JWT (JSON Web Token) is a secure token system used for API authentication.
JWT Flow

  • User logs in
  • Server validates credentials
  • Server generates token
  • Client sends token in every request

Install JWT Package
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

JWT Configuration
Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,

        ValidIssuer = "MyAPI",
        ValidAudience = "MyAPIUser",

        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes("THIS_IS_SECRET_KEY_123456"))
    };
});

var app = builder.Build();

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

app.Run();


Generate JWT Token

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;

public string GenerateToken(string username)
{
    var claims = new[]
    {
        new Claim(ClaimTypes.Name, username)
    };

    var key = new SymmetricSecurityKey(
        Encoding.UTF8.GetBytes("THIS_IS_SECRET_KEY_123456"));

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

    var token = new JwtSecurityToken(
        issuer: "MyAPI",
        audience: "MyAPIUser",
        claims: claims,
        expires: DateTime.Now.AddHours(1),
        signingCredentials: creds);

    return new JwtSecurityTokenHandler().WriteToken(token);
}

Secure API Controller
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    [HttpGet]
    public IActionResult GetData()
    {
        return Ok("Secure Data");
    }
}

5. API Key Security
API Key is a secret key sent in request headers.

Example:
x-api-key: ABC123XYZ

Middleware Example
public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string APIKEY = "MY_SECRET_KEY";

    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue("x-api-key", out var extractedApiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("API Key Missing");
            return;
        }

        if (!APIKEY.Equals(extractedApiKey))
        {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsync("Invalid API Key");
            return;
        }

        await _next(context);
    }
}

Register Middleware
app.UseMiddleware<ApiKeyMiddleware>();

6. IP Whitelisting Security
Only allowed IP addresses can access APIs.

Example:

  • Government APIs
  • Banking APIs
  • Internal APIs

Middleware Example
public class IPWhitelistMiddleware
{
    private readonly RequestDelegate _next;

    private readonly List<string> allowedIPs = new()
    {
        "127.0.0.1",
        "192.168.1.10"
    };

    public IPWhitelistMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var remoteIp = context.Connection.RemoteIpAddress?.ToString();

        if (!allowedIPs.Contains(remoteIp))
        {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsync("IP Not Allowed");
            return;
        }

        await _next(context);
    }
}


7. SQL Injection Protection
Dangerous Code

Wrong:
string query = "SELECT * FROM Users WHERE Name='" + username + "'";

Attacker Input:
' OR 1=1 --

This can expose all records.

Secure Code
Correct:
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Users WHERE Name=@Name", conn);
cmd.Parameters.AddWithValue("@Name", username);


8. Password Hashing Security
Never Store Plain Passwords


Wrong:
Password = 123456

Correct:
Password = Hashed Value

Password Hashing Example
using BCrypt.Net;
string hash = BCrypt.Net.BCrypt.HashPassword("123456");
bool verify = BCrypt.Net.BCrypt.Verify("123456", hash);

9. Rate Limiting Protection
Limits number of requests.

Protects from:

  • DDoS
  • Spam
  • Brute-force attacks

ASP.NET Core Rate Limiting
Program.cs

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("fixed", opt =>
    {
        opt.PermitLimit = 10;
        opt.Window = TimeSpan.FromMinutes(1);
    });
});

app.UseRateLimiter();

Apply Rate Limit
[EnableRateLimiting("fixed")]
[HttpGet]
public IActionResult Get()
{
    return Ok();
}

10. CORS Security
CORS controls which frontend domains can access API.
Enable Secure CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowMyApp",
        policy =>
        {
            policy.WithOrigins("https://myapp.com")
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
});

app.UseCors("AllowMyApp");


11. Request Validation Security
Validate incoming data.
Example
public class LoginModel
{
    [Required]
    public string Username { get; set; }

    [Required]
    [MinLength(6)]
    public string Password { get; set; }
}


12. Secure Headers
Add Security Headers
app.Use(async (context, next) =>
{
    context.Response.Headers.Add("X-Frame-Options", "DENY");
    context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");

    await next();
});


13. Logging and Monitoring
Why Important?


Detect:

  • Hacking attempts
  • Failed logins
  • Suspicious activities

Example
try
{
    // code
}
catch(Exception ex)
{
    _logger.LogError(ex.Message);
}


14. Swagger Security
Protect Swagger in Production

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

15. OAuth2 Security (Advanced)
OAuth2 allows login using:

  • Google
  • Microsoft
  • Facebook
  • GitHub

Used in enterprise systems.

16. Refresh Token Security
Why Needed?

JWT expires quickly.

Refresh Token helps generate new token without login.

17. Data Encryption
Encrypt Sensitive Data

Example:

  • Aadhaar Number
  • PAN Number
  • Bank Details

AES Encryption Example
using System.Security.Cryptography;

Use AES encryption for highly sensitive data.

18. CSRF Protection

Stops fake requests from external websites.
Mostly important in cookie-based authentication.

19. Security Best Practices

Best PracticeDescription

Use HTTPS

Encrypt communication

Use JWT

Secure authentication

Use Hashing

Protect passwords

Validate Inputs

Stop invalid data

Use Parameterized Queries

Stop SQL Injection

Use Rate Limiting

Prevent abuse

Enable Logging

Detect attacks

Restrict Swagger

Protect API docs

Use CORS

Restrict domains

Use IP Whitelist

Restrict access

20. Enterprise-Level Security Architecture

Recommended Flow

Client App
   ↓
API Gateway
   ↓
WAF Firewall
   ↓
Rate Limiter
   ↓
JWT Authentication
   ↓
Authorization
   ↓
Controller
   ↓
Database

21. Common API Attacks

AttackSolution

SQL Injection

Parameterized Query

XSS

Encode Output

Brute Force

Rate Limiting

Token Theft

HTTPS

DDoS

Firewall + Rate Limit

CSRF

Anti-Forgery Token

22. Example of Fully Secure API Request

POST /api/user/profile
Host: example.com
Authorization: Bearer TOKEN
x-api-key: APIKEY123
Content-Type: application/json


23. Advanced Enterprise Security Features
Multi-Factor Authentication (MFA)


Extra security layer:

  • OTP
  • Email verification
  • Authenticator apps

Device Tracking
Track:

  • IP
  • Browser
  • Device ID

Audit Trail
Store:

  • Login history
  • User actions
  • Data changes

24. Recommended Security Packages

PackageUse
Microsoft.AspNetCore.Authentication.JwtBearer JWT
BCrypt.Net Password Hashing
Serilog Logging
FluentValidation Validation
AspNetCoreRateLimit Rate Limiting

25. Final Recommended Secure Setup

For production ASP.NET Core API:

  • HTTPS
  • JWT Authentication
  • API Key
  • IP Whitelist
  • Rate Limiting
  • Logging
  • SQL Injection Protection
  • Password Hashing
  • CORS
  • Secure Headers
  • Audit Logs
  • Encryption

HostForLIFE.eu ASP.NET Core 10.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 

 



ASP.NET Core 10.0 Hosting - HostForLIFE.eu :: Overview of the.NET Web Development Ecosystem and Technologies

clock May 18, 2026 07:56 by author Peter

Microsoft developed the.NET Platform & Ecosystem as a software development environment for creating contemporary applications, including online, desktop, mobile, cloud, and gaming apps. Although it supports several programming languages, C# is the most popular. A wide range of frameworks, libraries, tools, and runtime components are available in the.NET ecosystem to assist developers in creating scalable and high-performing applications. Key technologies include Blazor for interactive online user interface, Entity Framework Core for data access, ASP.NET Core for web development, and.NET MAUI for cross-platform desktop and mobile apps.

All things considered, the.NET ecosystem makes it possible for developers to use a unified development strategy to effectively create and implement applications across many platforms. 


What is.NET?
 
.NET is a software development platform developed by Microsoft that enables programmers to construct and execute a variety of programs, such as desktop software, mobile apps, cloud-based services, online applications, and APIs.

It offers:
An environment for running apps

A collection of libraries for typical programming tasks

Frameworks and tools to expedite development

Support for a variety of operating systems, including Linux, macOS, and Windows


Now, we will explore and understand the complete web technologies in the .NET ecosystem.

Types of .NET
1. .NET Framework

.NET Framework is the original Windows-only version of .NET introduced by Microsoft for building traditional desktop and web applications. It was mainly used with technologies such as ASP.NET, Windows Forms, WPF, and WCF for enterprise and Windows-based development.

2. .NET Core
.NET Core is a modern, lightweight, high-performance, and cross-platform version of .NET designed for modern application development. It supports Windows, Linux, and macOS, making it suitable for cloud applications, REST APIs, microservices, and containerized environments.

3. Modern .NET (.NET 5/6/7/8/9)

Modern .NET is the current unified platform that combines the best features of .NET Framework and .NET Core into a single ecosystem. It is used for building web applications, mobile apps, desktop software, cloud services, gaming applications, and AI-powered solutions.

Web Technologies in .NET
ASP (Active Server Pages)


ASP stands for Active Server Pages, an older server-side web technology introduced by Microsoft for creating dynamic web pages. It allowed developers to generate server-side content and build interactive websites before the introduction of the .NET platform.

Example:
A login page that dynamically validates a username and password using server-side VBScript.

ASP.NET (The Classic Framework)
Originally released in 2002, ASP.NET is the mature web framework designed for the Windows ecosystem. It runs on the full .NET Framework and is used to build dynamic websites, web applications, and web services.

ASP.NET provides technologies such as Web Forms, MVC, and Web API, allowing developers to build server-side applications using C# and the .NET Framework runtime.

Example:
An enterprise College management system built using ASP.NET MVC with SQL Server backend.

Types of ASP.NET
1. ASP.NET Web Forms

ASP.NET Web Forms is an event-driven framework used to build web applications using server controls and a drag and drop style development approach. It is mainly used in older enterprise applications.

Example:
A traditional school management system with form-based UI.

2. ASP.NET MVC

ASP.NET MVC is based on the Model-View-Controller architecture, providing better separation of concerns, maintainability, and control over HTML and routing. It is widely used for scalable web applications.

Example:
An e-commerce website like an online shopping portal.

3. ASP.NET Web API
ASP.NET Web API is used to build RESTful HTTP services that can be consumed by web, mobile, and desktop applications. It is mainly used for backend service development.

Example:
A mobile app backend that provides product data in JSON format.

4. WCF (Windows Communication Foundation)
WCF is a service-oriented communication framework in the .NET Framework used to build secure and distributed applications. It supports protocols like HTTP, TCP, MSMQ, and SOAP.

Example:
A banking system where multiple services communicate securely between departments.

ASP.NET Core (The Modern Redesign)

ASP.NET Core is a modern web development framework used with .NET Core and modern .NET (.NET 5/6/7/8/9). It is a complete redesign of ASP.NET, built for high performance, cloud-native applications, microservices, and cross-platform development.

It can run on Windows, Linux, and macOS.

Example:
A cloud-based API for food delivery apps like Swiggy or Zomato backend services.
Types of ASP.NET Core
1. ASP.NET Core MVC

ASP.NET Core MVC is the modern MVC framework used for building cross-platform web applications with clean architecture, dependency injection, and high performance.

Example:
A modern SaaS dashboard application.
2. ASP.NET Core Web API

ASP.NET Core Web API is designed for building fast, scalable RESTful APIs and microservices for cloud and frontend applications.

Example:
Backend service for a mobile banking application.
3. Razor Pages
Razor Pages is a simplified page-based framework in ASP.NET Core that makes web development easier by reducing complexity compared to MVC.

Example:
A simple blog or admin panel application.

4. Blazor

Blazor is a modern UI framework in ASP.NET Core that allows developers to build interactive web applications using C# instead of JavaScript.

Example:
A real-time chat application or interactive dashboard built entirely using C#.

5. Worker Service
A Worker Service is a type of application in modern .NET created by Microsoft that is used to run long-running background tasks without any user interface. It is mainly used for background processing like scheduled jobs, message queue handling, email sending, or continuous data processing and works well in cloud and container environments like Docker and Azure.

Example:
A Worker Service can be used in an e-commerce system to process order payments in the background once a user places an order, the service continuously checks the order queue and processes payment, updates inventory, and sends confirmation emails automatically without user interaction.

Conclusion
Web Technologies in .NET provide a complete evolution from classic ASP to modern ASP.NET Core, showing how web development in Microsoft has grown into a powerful, scalable, and cross-platform ecosystem. It enables developers to build everything from simple dynamic websites to high-performance cloud-based APIs and enterprise applications.

HostForLIFE.eu ASP.NET Core 10.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 10.0 Hosting - HostForLIFE.eu :: Using TreatWarningsAsErrors to Improve Code Reliability in.NET

clock May 12, 2026 08:23 by author Peter

Writing code that is secure, dependable, manageable, and free of hidden problems is just as important as writing code that works when creating high-quality software. The.NET compiler produces warnings during development anytime it finds possible issues with the program. Since the application still builds correctly, many developers frequently disregard these warnings. Unresolved warnings, however, may eventually result in unpredictable application behavior, performance problems, security flaws, or runtime failures.

In order to overcome this difficulty,.NET has a potent MSBuild property known as:
TreatWarningsAsErrors>true

All compiler warnings are handled as build errors when enabled, requiring developers to fix problems before the application can be successfully constructed.

Why Compiler Warnings Should Not Be Ignored?

Compiler warnings are generated for situations such as:

  • Possible null reference issues
  • Unused variables or methods
  • Obsolete API usage
  • Async methods without await
  • Potential security concerns
  • Package compatibility issues

What is <TreatWarningsAsErrors>?
The <TreatWarningsAsErrors> property instructs the compiler to fail the build whenever a warning is detected
Add the following property inside the .csproj file:
<PropertyGroup>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

Once enabled:

  • Warnings become compilation errors
  • Developers must fix warnings before committing code
  • CI/CD pipelines fail if warnings exist
  • Code quality standards improve significantly

Using Specific Warning Configurations
Treat Specific Warnings as Errors
In some scenarios, teams may want to treat only selected warnings as errors.
<PropertyGroup>
    <WarningsAsErrors>CS8602;CS1998</WarningsAsErrors>
</PropertyGroup>


This configuration treats only:
CS8602 -Possible null reference
CS1998 - Async method without await

as build errors.

Ignore Specific Warnings
You can also suppress specific warnings if required:
<PropertyGroup>
    <NoWarn>CS8601</NoWarn>
</PropertyGroup>

This suppresses a possible null reference assignment.

Summary

Enabling <TreatWarningsAsErrors>true</TreatWarningsAsErrors> in .NET applications helps developers identify and fix potential issues during the build process itself. It improves code quality, reduces technical debt, and prevents many runtime failures from reaching production environments. Adopting this practice in modern .NET development ensures cleaner, more maintainable, and enterprise-ready application.

HostForLIFE.eu ASP.NET Core 10.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 10.0 Hosting - HostForLIFE.eu :: How to Use.NET MAUI to Create a Cross-Platform Mobile Application?

clock May 8, 2026 10:19 by author Peter

It is typically necessary to learn several technologies in order to create mobile apps for both iOS and Android. On the other hand, you can use C# and a single codebase to create cross-platform mobile applications with.NET MAUI (Multi-platform App UI), which is an extension of Xamarin.Forms and is intended for contemporary, scalable, and high-performance desktop and mobile applications. It enables developers to write once and use it on Windows, macOS, iOS, and Android.

Using real-world examples and best practices, we will lead you through the process of creating a cross-platform mobile application from scratch using.NET MAUI.

What is .NET MAUI?
.NET MAUI is a cross-platform framework that enables developers to create native mobile apps using C# and XAML.

Key benefits:

  • Single codebase for Android and iOS
  • Native performance
  • Access to device features like camera, GPS, and storage
  • Strong integration with .NET ecosystem
  • Prerequisites for .NET MAUI Development
  • Before starting, make sure your system is ready.

Requirements:

  • Install Visual Studio with .NET MAUI workload
  • Install Android SDK and Emulator
  • Install Xcode (for iOS development on Mac)

Why this matters:

  • Ensures smooth development experience
  • Avoids setup issues later

Step 1: Create a New .NET MAUI Project
Open Visual Studio and select:

  • Create a new project
  • Choose ".NET MAUI App"
  • Project structure includes:
  • Platforms (Android, iOS)
  • Resources (images, fonts)
  • MainPage.xaml (UI)
  • MainPage.xaml.cs (logic)

Step 2: Understand the Project Structure
.NET MAUI uses a single project structure.

Important folders:

  • Platforms: Platform-specific code
  • Resources: Images, fonts, styles
  • App.xaml: Global styles and configuration

This structure helps in maintaining a clean and scalable codebase.

Step 3: Design the UI Using XAML
XAML is used to design the user interface.

Example:
<VerticalStackLayout Padding="20">
    <Label Text="Welcome to .NET MAUI" FontSize="24" />
    <Button Text="Click Me" Clicked="OnButtonClicked" />
</VerticalStackLayout>


This creates a simple UI with a label and a button.

Why this is useful:

  • Clean separation of UI and logic
  • Easy to maintain and update design

Step 4: Add Code Behind Logic
In MainPage.xaml.cs:
private void OnButtonClicked(object sender, EventArgs e)
{
    DisplayAlert("Hello", "Button clicked!", "OK");
}

This handles user interaction.

Step 5: Run the App on Android Emulator
Select Android Emulator
Click Run

You will see your app running on Android.

Step 6: Run the App on iOS Simulator

  • Connect Mac (required for iOS)
  • Select iOS Simulator

This ensures your app works on both platforms.

Step 7: Use MVVM Pattern (Best Practice)
MVVM (Model-View-ViewModel) helps organize code.

Benefits:

  • Better separation of concerns
  • Easier testing
  • Cleaner code structure

Example ViewModel:
public class MainViewModel
{
    public string Title { get; set; } = "Hello MAUI";
}

Step 8: Access Device Features
.NET MAUI allows access to native features.
Example: Get device location
var location = await Geolocation.GetLastKnownLocationAsync();

Use cases:

  • GPS tracking
  • Camera apps
  • File storage

Step 9: Add Navigation Between Pages
Example:
await Navigation.PushAsync(new SecondPage());

Why this matters:

  • Enables multi-screen apps
  • Improves user experience

Step 10: Handle Data and APIs
You can call APIs using HttpClient.

Example:
var client = new HttpClient();
var data = await client.GetStringAsync("https://api.example.com/data");

This is useful for:

  • Fetching data from servers
  • Building real-world apps

Step 11: Optimize Performance
Best practices:

  • Use async/await
  • Avoid heavy UI operations
  • Optimize images

Why:

  • Improves app speed
  • Enhances user experience

Step 12: Test Your App
Testing ensures your app works correctly.

Types of testing:

  • UI testing
  • Unit testing
  • Device testing

Step 13: Publish Your App
Steps:

  • Build release version
  • Generate APK/IPA
  • Upload to Play Store / App Store
  • Real-World Example

Imagine building a To-Do app:

Features:

  • Add tasks
  • Delete tasks
  • Save data locally

This simple app can run on both Android and iOS using the same code.

Common Mistakes to Avoid

  • Not using MVVM pattern
  • Ignoring performance optimization
  • Hardcoding UI values
  • Not testing on real devices

Summary
.NET MAUI makes it easy to build cross-platform mobile applications for Android and iOS using a single codebase and C#. By following a structured approach, using XAML for UI, MVVM for architecture, and best practices for performance, developers can create scalable, high-performance mobile apps. It is a powerful solution for modern mobile app development, helping developers save time, reduce costs, and deliver high-quality applications efficiently.

HostForLIFE.eu ASP.NET Core 10.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 10.0 Hosting - HostForLIFE ::Overview of ASP.NET Core Web API JSON Serialization

clock May 4, 2026 09:06 by author Peter

The process of transforming C# objects into JSON strings (for responses) and back again (for request bodies) is known as JSON serialization in ASP.NET Core Web API. Although ASP.NET Core takes care of this automatically by default, creating professional APIs requires knowing how to customize it.

[HttpGet]
public IActionResult GetUser()
{
    var user = new User { Id = 1, Name = "Alice" };
    return Ok(user); // Automatically serialized to {"id": 1, "name": "Alice"}
}


2. Configuration & Global Settings
You can customize serialization behavior globally in your Program.cs. Common tasks include enabling "pretty printing" (indentation) or changing how property names are cased.

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        // 1. Indent the JSON for readability
        options.JsonSerializerOptions.WriteIndented = true;

        // 2. Ignore properties that are null
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

        // 3. Keep property names as they are in C# (PascalCase) instead of camelCase
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
    });


3. Using Attributes for Fine Control

Sometimes you only want to change serialization for a specific class or property. You can use attributes directly on your models:

Attribute Purpose
[JsonPropertyName("user_id")] Renames the property in the JSON output.
[JsonIgnore] Prevents the property from being serialized at all.
[JsonInclude] Forces a private property to be included.
[JsonConstructor] Tells the serializer which constructor to use for deserialization.

Example:

public class Product
{
    [JsonPropertyName("sku_code")]
    public string Sku { get; set; }

    [JsonIgnore]
    public decimal InternalCost { get; set; }
}


4. System.Text.Json vs. Newtonsoft. Json

While System.Text.Json is the default, many legacy or complex projects still use Newtonsoft.Json (Json.NET).

Feature System.Text.Json (Default) Newtonsoft.Json (Json.NET)
Performance Faster, uses less memory. Slower due to heavy reflection.
Compatibility Built into .NET. Requires a NuGet package.
Features Strict, standard-compliant. Highly flexible, handles edge cases easily.
Native AOT Fully supported (via Source Gen). Not supported.

How to switch to Newtonsoft.Json:
If you need specific features like JsonPatch or complex reference handling, install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package and update Program.cs:
builder.Services.AddControllers().AddNewtonsoftJson();

5. Best Practices for 2026
Stick to System.Text.Json: Unless you have a specific technical debt reason to use Newtonsoft, the performance gains and security of the built-in library are worth it.
Use Source Generation: For high-traffic APIs or Cloud Native/Native AOT apps, use JSON Source Generators to eliminate reflection at runtime.
Avoid Circular References: If your models reference each other (e.g., Parent → Child → Parent), use ReferenceHandler.IgnoreCycles to prevent the serializer from crashing.
Contracts First: Always define DTOs (Data Transfer Objects) specifically for your API rather than serializing your Database Entities directly.

Are you looking to migrate an existing project from Newtonsoft.Json, or are you starting a fresh project from scratch?



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.


Month List

Tag cloud

Sign in