Tuesday, 5 August 2025

How Can I Switch to .NET 6/7/8 from.NET Framework?

Leave a Comment

In contrast to the outdated.NET Framework (which is Windows-only and in maintenance mode), modern.NET is quick, light, cross-platform, and constantly evolving. It's time to upgrade to.NET 6,.NET 7, or the most recent.NET 8 (LTS) if you're still developing apps in the.NET Framework.

 1. Why Migrate?

Advantages of migrating

  • Cross-platform support (Linux, macOS)
  • Better performance and memory usage
  • Access to modern APIs (gRPC, Minimal APIs, AOT, Blazor)
  • Native container and cloud support
  • Future LTS releases

Risks of staying

  • No new features in .NET Framework
  • Limited support for modern tooling
  • Security and compatibility issues
2. Assess Your Current App

Use the Try Convert tool or the Portability Analyzer to check compatibility.

Tool Example

dotnet tool install -g upgrade-assistant
upgrade-assistant analyze MyApp.csproj

Key things to check

  • Is it a Web Forms or WCF app? (These are harder to migrate)
  • Does it rely on Windows-only APIs (e.g., System.Drawing)?
  • Any third-party dependencies that don’t support .NET 6+?
3. Prepare the Project for Migration

Checklist Before Migration

  • Backup your project (Git or ZIP)
  • Upgrade to the latest .NET Framework version (like 4.8)
  • Remove or isolate deprecated APIs
  • Update all NuGet packages
4. Convert the Project File

Old .csproj files in .NET Framework are verbose. In .NET Core and later, you use the SDK-style project format.

Example Conversion

Old .csproj (.NET Framework)

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Reference Include="System" />
  ...
</Project>

New .csproj (.NET 6+)

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

You can automate this using

dotnet try-convert --project MyApp.csproj
5. Migrate Codebase
Common Changes Needed

Old API Modern Alternative
System.Web ASP.NET Core
WebForms Not supported (rebuild with Blazor or MVC)
WCF Use gRPC or CoreWCF
ConfigurationManager.AppSettings IConfiguration
HttpContext.Current HttpContext via DI

Example: Replacing AppSettings
// Old
string key = ConfigurationManager.AppSettings["MyKey"];

// New
var config = builder.Configuration;
string key = config["MyKey"];
6. Test Your App on .NET 6/7/8

Run your app using:

dotnet run

Test in these areas

  • Web endpoints
  • Database access (EF Core)
  • Background tasks
  • Logging and configuration

Unit tests and integration tests should be updated and re-run.

7. Choose Target .NET Version
Version Use When
.NET 6 LTS support till Nov 2024
.NET 7 Non-LTS, experimental/short-lived apps
.NET 8 LTS till Nov 2026 – Recommended for new or upgraded apps

8. Upgrade with .NET Upgrade Assistant

The official Microsoft tool:

dotnet tool install -g upgrade-assistant
upgrade-assistant upgrade MyApp.sln

Features

  • Analyzes the solution
  • Converts project files
  • Suggests code replacements
  • Keeps code structure intact
9. Containerize (Optional but Powerful)

Modern .NET apps run well in containers.

# Dockerfile
FROM mcr.microsoft.com/dotnet/aspnet:8.0
COPY ./publish /app
WORKDIR /app
ENTRYPOINT ["dotnet", "MyApp.dll"]

Use

docker build -t myapp .
docker run -p 5000:80 myapp
10. Troubleshooting Tips
Problem Solution
Missing APIs Look for NuGet alternatives
Build errors Check deprecated syntax or missing references
Third-party libs Check for .NET Standard or .NET 6+ versions
ASP.NET WebForms Rebuild using Blazor (no direct upgrade path)

Final Thoughts
Migrating from .NET Framework to .NET 6/7/8 is a strategic move toward:
  • Performance
  • Cloud-readiness
  • Long-term sustainability

While it may seem complex, Microsoft’s tooling and community support make the journey smoother than ever.

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...

Thursday, 31 July 2025

A Comprehensive Guide on ASP.NET Web API in Easy-to-Understand Language

Leave a Comment

ASP.NET Web API is a framework used to build HTTP services in NET. It helps developers create APIs that can be used by different clients like web apps, mobile apps, and desktop apps. These APIs use HTTP methods like GET, POST, PUT, and DELETE to handle data. It is lightweight and flexible, and it supports content negotiation (like returning JSON or XML). This cheatsheet covers the most important concepts of Web API in a short and clear format, with examples for each topic. This is helpful if you are learning or revising Web API.

1. What is Web API?

  • Definition: Web API is a framework for building RESTful services using HTTP.
  • Key Point: It is part of ASP.NET and supports both MVC-style routing and attribute routing.

2. Creating a Web API Project

// In Visual Studio:
// File > New > Project > ASP.NET Web Application > Web API template

Key Point: A default controller (like ValuesController) is already created in the template.

3. API Controller

Definition: A controller handles HTTP requests in a Web API.

public class ProductsController : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "Product1", "Product2" };
    }
}

Key Point: It should inherit from ApiController (or ControllerBase in .NET Core).

4. Routing

Definition: Routing maps the request URL to a controller and action.

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Key Point: Web API uses a different routing system than MVC by default.

5. Attribute Routing

Definition: You can define routes using attributes on controller actions.

[Route("api/products/{id}")]
public string GetProduct(int id)
{
    return "Product " + id;
}

Key Point: Enable it using config.MapHttpAttributeRoutes(); in WebApiConfig.

6. HTTP Methods

Definition: Web API supports standard HTTP methods like GET, POST, PUT, and DELETE.

// GET
public string Get() => "data";

// POST
public void Post([FromBody] string value) { }

// PUT
public void Put(int id, [FromBody] string value) { }

// DELETE
public void Delete(int id) { }

Key Point: Method name must start with Get, Post, Put, or Delete.

7. FromBody and FromUri

Definition: They are used to get input data from the request body or URI.

public void Post([FromBody] Product product) { }

public IHttpActionResult Get([FromUri] int id) { }

Key Point: Use [FromBody] for complex types in POST/PUT. [FromUri] is used for simple query parameters.

8. Return Types

Definition: Return types can be plain data, IHttpActionResult, or HttpResponseMessage.

public IHttpActionResult Get()
{
    return Ok("Hello");
}

Key Point: IHttpActionResult gives more control and better testability.

9. Dependency Injection

Definition: Inject services like repositories into controllers.

public class ProductsController : ApiController
{
    private IProductService _service;
    public ProductsController(IProductService service)
    {
        _service = service;
    }
}

Key Point: Use Unity, Autofac, or a built-in DI container in .NET Core.

10. Content Negotiation

  • Definition: Web API can return data in JSON or XML based on the client's request.
  • Key Point: Set Accept header in the request (application/json or application/xml).

11. Model Validation

Definition: Validate input data using [Required], [StringLength], etc.

public class Product
{
    [Required]
    public string Name { get; set; }
}

Key Point: Check ModelState.IsValid in the controller action.

12. Exception Handling

Definition: Handle errors using try-catch, Exception Filters, or global handlers.

[HttpGet]
public IHttpActionResult Get(int id)
{
    try
    {
        var product = GetProductById(id);
        return Ok(product);
    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }
}

Key Point: Global filters can be added using GlobalConfiguration.Configuration.Filters.

13. Cross-Origin Requests (CORS)

Definition: Allows your API to be called from a different domain.

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ProductsController : ApiController
{
}

Key Point: Install Microsoft.AspNet.WebApi.Cors NuGet package and enable CORS in WebApiConfig.

14. Token Authentication (Basic)

  • Definition: Secure APIs using tokens like JWT.
  • Key Point: In real-world projects, always protect APIs using authentication and authorization.

15. Calling Web API

From jQuery

$.get("api/products", function(data) {
    console.log(data);
});

From C#

HttpClient client = new HttpClient();
var response = await client.GetAsync("http://localhost/api/products");

Key Point: Use HttpClient to call APIs from C# code.

16. Custom Routes

Definition: You can define specific routes for controller actions.

[Route("api/products/search/{name}")]
public IHttpActionResult SearchByName(string name)
{
    // logic
}

Key Point: Useful for actions that don’t follow standard REST routes.

17. Status Codes

Definition: Use proper HTTP status codes (200, 201, 400, 404, 500, etc.)

return StatusCode(HttpStatusCode.Created);
return BadRequest("Invalid data");

Key Point: Follow standard codes for better API client support.

18. Quick Swagger Setup (Overview)

  • Definition: Use Swagger to auto-generate API documentation.
  • Key Point: Install the Swashbuckle NuGet package and enable it to test APIs via browser.

19. API Versioning

Definition: Allows you to manage different versions of your API without breaking existing clients.

[RoutePrefix("api/v1/products")]
public class ProductsV1Controller : ApiController { }

[RoutePrefix("api/v2/products")]
public class ProductsV2Controller : ApiController { }

Key Point: Helps maintain backward compatibility. You can version by route, query string, or header.

20. Action Results (Common IHttpActionResult Methods)

Definition: Returns specific types of responses.

return Ok();                   // 200 OK
return NotFound();             // 404 Not Found
return BadRequest();           // 400 Bad Request
return StatusCode(HttpStatusCode.Created);  // 201 Created
return InternalServerError(); // 500 Internal Server Error

Key Point: Use these for clear and meaningful API responses.

21. Throttling / Rate Limiting

  • Definition: Limits the number of requests a user/client can make in a period.
  • Key Point: Not built-in by default in classic Web API. You can use message handlers or third-party packages like WebApiThrottle.

22. Filters (Action Filters, Exception Filters, etc.)

Definition: Used to run code before/after actions globally or per controller/action.

public class LogFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        // logging logic
    }
}

Key Point: Useful for cross-cutting concerns like logging, validation, and exception handling.

23. Custom Middleware / Delegating Handlers

Definition: Middleware that processes HTTP requests/responses at a low level.

public class CustomHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Custom logic
        return await base.SendAsync(request, cancellationToken);
    }
}

Key Point: Great for logging, authentication, or modifying requests globally.

24. Async and Await Support

Definition: Web API fully supports async programming for non-blocking I/O.

public async Task<IHttpActionResult> Get()
{
    var data = await _service.GetDataAsync();
    return Ok(data);
}

Key Point: Always use async for I/O-bound operations (database, API calls) to improve performance.

25. Logging

  • Definition: You can use frameworks like NLog, Serilog, or log4net to log information from your Web API.
  • Key Point: Log errors, warnings, and user actions for debugging and audit purposes.

26. API Security Basics

Definition: Protect APIs using techniques like.

  • HTTPS only
  • Token-based authentication (JWT)
  • Role-based access control
  • API keys

Key Point: Security is critical. Always validate inputs, sanitize outputs, and follow secure coding practices.

27. Full Swagger/OpenAPI Integration (Advanced)

Definition: Swagger (via the Swashbuckle package) auto-generates UI documentation for your Web API.

// Install-Package Swashbuckle
// In WebApiConfig.cs
config.EnableSwagger(c => {
    c.SingleApiVersion("v1", "Product API");
}).EnableSwaggerUi();

Key Point: Allows easy testing and visual exploration of endpoints. Makes APIs self-explanatory.

28. Authentication and Authorization

Definition: Use filters or middleware to restrict access based on roles, claims, or tokens.

[Authorize(Roles = "Admin")]
public class AdminController : ApiController { }

Key Point: Combine the Authorize attribute with JWT Bearer or OAuth 2.0 for secure APIs.

29. Token-Based Authentication (JWT)

  • Definition: Use JWT (JSON Web Tokens) to authenticate API clients.
  • Key Point: JWT tokens are stateless, compact, and ideal for securing APIs. Use middleware or filters to validate.

30. Role-Based and Claims-Based Access

Definition: Control access using user roles or custom claims inside tokens.

[Authorize(Roles = "Manager")]
public class ReportsController : ApiController { }

Key Point: Fine-grained control over who can access what.

31. Global Error Handling

Definition: Use ExceptionHandler or ExceptionLogger to catch and log unhandled exceptions globally.

public class GlobalExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        context.Result = new InternalServerErrorResult(context.Request);
    }
}

Key Point: Avoid leaking stack traces. Always return user-friendly error messages.

32. Request and Response Logging

  • Definition: Log complete HTTP request and response lifecycle for audit/debugging.
  • Key Point: Use DelegatingHandler or middleware. Avoid logging sensitive data (like passwords or tokens).

33. API Response Wrapping

Definition: Standardize all responses in a consistent format.

{
  "status": "success",
  "data": {...},
  "message": null
}

Key Point: Improves client-side error handling and debugging.

34. Custom Model Binders

Definition: Used to bind request data to complex objects when default binding fails.

public class CustomBinder : IModelBinder { ... }

Key Point: Useful for binding non-standard formats or when data comes from mixed sources.

35. Caching Responses

Definition: Use OutputCache, custom headers, or memory cache to store repeated results.

[OutputCache(Duration = 60, VaryByParam = "none")]
public IHttpActionResult Get() { ... }

Key Point: Improves performance for read-heavy APIs. Avoid caching sensitive or changing data.

36. Media Formatters

Definition: Customize how data is serialized (e.g., JSON, XML, CSV) using formatters.

config.Formatters.JsonFormatter.SerializerSettings.Formatting =
    Formatting.Indented;

Key Point: Remove XML formatter if you want only JSON: config.Formatters.Remove(config.Formatters.XmlFormatter);

37. Enforcing HTTPS in ASP.NET Web API

  • Definition: Force all incoming API requests to use HTTPS instead of HTTP.
  • Implementation: ASP.NET Web API does not support [RequireHttps] natively like MVC. To enforce HTTPS, use a custom DelegatingHandler or configure it at the IIS/hosting level.

Example (Custom DelegatingHandler)

public class RequireHttpsHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            return Task.FromResult(
                request.CreateResponse(HttpStatusCode.Forbidden, "HTTPS is required")
            );
        }
        return base.SendAsync(request, cancellationToken);
    }
}

Register the handler in WebApiConfig.cs.

config.MessageHandlers.Add(new RequireHttpsHandler());

Key Point: There is no built-in [RequireHttps] in Web API. Use a custom handler or enforce HTTPS at the IIS/server level. Never expose APIs handling sensitive data over plain HTTP.

38. Handling Multipart Form Data

  • Definition: Used for uploading files, images, or form data using HTTP POST.
  • Key Point: Manually parse MultipartContent and always validate file type/size.

39. Using HTTP PATCH for Partial Updates

Definition: Use PATCH when only some fields need to be updated.

[HttpPatch]
public IHttpActionResult Patch(int id, JsonPatchDocument<Product> patchDoc) { ... }

Key Point: Install support via Microsoft.AspNet.WebApi.JsonPatch (or write custom logic).

40. API Gateways and Aggregation

  • Definition: Build a unified interface over multiple APIs, usually done using API gateways like Ocelot.
  • Key Point: Useful in microservices architecture to reduce client complexity.

41. Using HATEOAS (Hypermedia as the Engine of Application State)

Definition: Add navigational links in your API responses.

{
  "id": 1,
  "name": "Item",
  "links": [
    { "rel": "self", "href": "/api/items/1" },
    { "rel": "delete", "href": "/api/items/1" }
  ]
}

Key Point: Improves discoverability and client navigation.

42. API Testing Tools

  • Definition: Use Postman, Swagger UI, or REST Client in VS Code to test your APIs.
  • Key Point: Always test edge cases, invalid inputs, and unauthorized access.

43. Handling Circular References in JSON

Definition: Avoid JSON serialization errors caused by self-referencing objects.

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
    ReferenceLoopHandling.Ignore;

Key Point: Avoid exposing entire object graphs to the client.

44. API Deployment Considerations

  • Definition: APIs should be deployed with proper versioning, environment configs, HTTPS, and monitoring.
  • Key Point: Use CI/CD pipelines, set environment variables, and add observability (logs, health checks, alerts).

45. Message Handlers (Custom HTTP Pipeline Processing)

Definition: DelegatingHandler lets you intercept HTTP requests/responses globally.

public class LoggingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Logging logic
        return await base.SendAsync(request, cancellationToken);
    }
}

Key Point: Ideal for custom authentication, logging, headers, correlation IDs, etc.

46. Conditional Requests (ETag / If-Modified-Since)

Definition: Improve performance by letting the client cache responses and check if the data has changed.

var response = Request.CreateResponse(HttpStatusCode.OK, product);
response.Headers.ETag = new EntityTagHeaderValue("\"12345\"");

Key Point: Avoid sending full data again if nothing has changed. Useful for read-heavy APIs.

47. HTTP OPTIONS and Preflight Requests (CORS Handling)

  • Definition: Browsers send OPTIONS requests before certain CORS requests to check if they are allowed.
  • Key Point: Ensure Web API correctly handles the OPTIONS method for cross-origin calls, especially with authentication.

48. Health Checks / Readiness Probes

Definition: Custom endpoints to report API health to load balancers or monitoring tools.

[Route("api/health")]
public IHttpActionResult HealthCheck() => Ok("Healthy");

Key Point: Needed for Kubernetes, Azure App Services, or any auto-scaling infra.

49. API Auditing

  • Definition: Track who did what, when, and where for security/compliance.
  • Key Point: Log critical changes (data updates/deletes), with user and IP info. Essential in finance/healthcare APIs.

50. IP Whitelisting

  • Definition: Only allow access to the API from approved IP addresses.
  • Key Point: Handled via reverse proxies (e.g., Nginx, IIS), but you can add middleware or custom handlers too.

51. Rate Limiting via Custom Throttling

  • Definition: Restrict how many requests a user or IP can make within a time window.
  • Key Point: Build your own or use packages like WebApiThrottle. Protects against brute force and DoS attacks.

52. Response Compression (GZip)

Definition: Reduce payload size using compression (e.g., GZip).

config.MessageHandlers.Add(
    new ServerCompressionHandler(
        new GZipCompressor(),
        new DeflateCompressor()
    )
);
C#

Key Point: Improves performance, especially for large responses.

53. API Lifecycle Management

  • Definition: Versioning, deprecation notices, sunsetting old endpoints, and backward compatibility.
  • Key Point: Plan versioning before you go live. Always give clients time to migrate.

54. Localization / Globalization

  • Definition: Return API messages or formats based on the user’s locale/culture.
  • Key Point: Support multilingual clients (e.g., date/time/currency formats).

55. OpenAPI Extensions and Code Generation

  • Definition: Generate client SDKs (C#, TypeScript, etc.) using OpenAPI (Swagger) spec.
  • Key Point: Reduces front-end/back-end mismatch. Improves API adoption.

56. Using API Management Tools (Azure API Management, Kong, etc.)

  • Definition: These tools provide central control over versioning, throttling, monitoring, authentication, and analytics.
  • Key Point: Vital for large-scale APIs in production. Integrates well with cloud CI/CD.

57. WebSockets or SignalR Integration (Not Typical but Possible)

  • Definition: Though Web API is REST-based, you can pair it with SignalR for real-time features.
  • Key Point: Use Web API for CRUD and SignalR for notifications/updates in real time.

58. Using Filters for Response Shaping (Fields Selection)

Definition: Allow clients to choose only specific fields in response to reduce payload.

GET /api/products?fields=name,price

Key Point: Improves performance on mobile clients or limited-bandwidth situations.

59. CQRS (Command Query Responsibility Segregation) in API Design

  • Definition: Separate read (query) and write (command) APIs for better scalability and clarity.
  • Key Point: Use command handlers and query handlers separately. Common in enterprise APIs.

60. Soft Deletes and Archival Endpoints

  • Definition: Don’t delete records from the DB. Mark them inactive and hide from regular queries.
  • Key Point: APIs should offer GET /deleted, GET /archived, or restore endpoints for auditability.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More...

Tuesday, 22 July 2025

ASP.NET Core's Entity Framework Core

Leave a Comment

 Entity Framework (EF) Core is a lightweight, flexible, open-source, and cross-platform version of the popular Entity Framework data access technology. It functions as an Object-Relational Mapper (ORM), removing the requirement for the majority of the data-access code that developers typically write and allowing.NET developers to work with a database using.NET objects.

In this article, we will walk through the process of setting up EF Core in an ASP.NET Core web application and performing basic CRUD operations.

Why Entity Framework Core?
  • Productivity: Auto-generates SQL scripts and manages migrations.
  • Maintainability: Makes code cleaner and more maintainable.
  • Testability: Supports dependency injection and in-memory databases.
  • Cross-platform: Works across Windows, macOS, and Linux.

Prerequisites

  • Visual Studio 2022 or later (or VS Code with .NET SDK).
  • .NET 6 or .NET 8 SDK installed.
  • Basic knowledge of C# and ASP.NET Core MVC.
Step-by-Step Implementation

Step 1. Create an ASP.NET Core MVC Project

Create a new project in Visual Studio.

File > New > Project > ASP.NET Core Web App (Model-View-Controller)

Ensure .NET 6.0 or .NET 8.0 is selected.

Step 2. Install Entity Framework Core Packages

Using NuGet Package Manager Console.

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools

Step 3: Define the Data Model

Create a model class under Models folder.

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Course { get; set; }
    public int Age { get; set; }
}

Step 4: Configure DbContext

Create a class AppDbContext.cs:

using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    public DbSet<Student> Students { get; set; }
}

Register this context in Program.cs

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")
    )
);

Add the connection string in appsettings.json.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=StudentDB;Trusted_Connection=True;"
  }
}

Step 5: Add a Controller and Views

Use the scaffold tool to generate a controller and views.

Add > Controller > MVC Controller with views, using Entity Framework
SQL

Choose the Student model and AppDbContext.

Step 6: Run Migrations

Add-Migration InitialCreate
Update-Database

This creates the database and tables.

Best Practices

  • Always validate input models.
  • Use async methods for better performance.
  • Use Repository Pattern for complex systems.

Challenges Faced

  • Initial migration issues if connection strings are misconfigured.
  • Model-property mismatches can throw runtime errors.
  • Limited debugging options compared to raw SQL.

Future Scope

  • Integrate EF Core with Azure SQL Database.
  • Use EF Core with APIs and microservices.
  • Explore advanced features like Query Tags, Global Filters, and Stored Procedures.

Author Information

  • Name: Mohammed Altaf
  • Expertise: C#, ASP.NET Core, ML, Data Engineering

Best SQL 2022 Hosting Recommendation

One of the most important things when choosing a good SQL 2019 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable SQL 2019, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast SQL 2019 hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for SQL 2019. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Wednesday, 16 July 2025

OpenTelemetry in.NET 9: Use Jaeger to Track Requests End-to-End

Leave a Comment

In today’s world of modern distributed systems, it’s very important to understand how a request moves across different services, especially when you are fixing bugs or trying to make things faster. With microservices, single-page apps (SPAs), asynchronous message queues, and multiple databases involved, tracking a single user’s request becomes quite challenging.

Fortunately, OpenTelemetry (OTel) has emerged as the open standard for collecting telemetry data, including traces, metrics, and logs. With .NET 9, developers can now easily add full tracing to their systems with even better support for OpenTelemetry, requiring minimal effort.

In this blog, we’ll see how you can trace a request starting from the browser, going through a .NET 9 backend, and all the way to the database using OpenTelemetry and Jaeger to view the trace data. We’ll also explain where the telemetry data is stored and how to maintain secure access to Jaeger in a production setup.

Why OpenTelemetry?

OpenTelemetry is an open-source toolset for observability, backed by the Cloud Native Computing Foundation (CNCF). It helps standardize how data, such as traces, logs, and metrics, is collected and shared across different systems.

Here are some key benefits.

  • Vendor-neutral: You can change your backend tools without affecting how you’ve written the monitoring code.
  • Works with many languages: Supports .NET, Java, JavaScript, Python, Go, and more.
  • Gives full context: You can capture traces, metrics, logs, baggage, and system details all together.

Whether you're building microservices, backend APIs, or frontend applications, OpenTelemetry provides a unified approach to understanding how your system operates in real-world scenarios.

Setting up Telemetry in .NET 9 Web API Project

Create a .NET 9 project and add the following NuGet packages to start capturing telemetry.

Install the necessary NuGet packages.

# In Visual Studio Code
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Http
dotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore
dotnet add package OpenTelemetry.Exporter.Jaeger

# In Visual Studio Package Manager Console
Install-Package OpenTelemetry.Extensions.Hosting
Install-Package OpenTelemetry.Instrumentation.AspNetCore
Install-Package OpenTelemetry.Instrumentation.Http
Install-Package OpenTelemetry.Instrumentation.EntityFrameworkCore
Install-Package OpenTelemetry.Exporter.Jaeger

Then in your Program.cs.

builder.Services.AddOpenTelemetry()
    .WithTracing(tracerProviderBuilder =>
    {
        tracerProviderBuilder
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddEntityFrameworkCoreInstrumentation()
            .AddOtlpExporter(options =>
            {
                options.Endpoint = new Uri("http://localhost:4317");
            });
    });

This automatically captures.

  • Incoming HTTP requests to your APIs
  • Outgoing HTTP calls (to other APIs)
  • SQL queries via EF Core
  • Propagation of trace context (traceId, spanId)
Frontend Project Setup: Tracing from the Browser

OpenTelemetry also works well with JavaScript-based single-page applications (SPAs), such as React or Angular. It helps you track important user activities, such as.

  • User clicks: what users are clicking on.
  • Page loads: how fast your pages are loading.
  • API calls: how your frontend is talking to the backend.

With this, you get a clear picture of how users are interacting with your app and how your frontend is performing. This is particularly useful for resolving issues and enhancing the user experience.

Need to install the below NPM dependencies.

npm install \
  @opentelemetry/api \
  @opentelemetry/sdk-trace-web \
  @opentelemetry/exporter-otlp-http

Now to set up the same need to add the below code.

import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { OTLPTraceExporter } from '@opentelemetry/exporter-otlp-http';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';

const provider = new WebTracerProvider();

provider.addSpanProcessor(
  new SimpleSpanProcessor(
    new OTLPTraceExporter({
      url: 'http://localhost:4318/v1/traces',
    })
  )
);

provider.register();
What is Jaeger?

Jaeger is an open-source tool for distributed tracing, originally developed by Uber. It helps you visualize how requests flow through various parts of your system.

Some of its key features.

  • A powerful and easy-to-use UI that shows traces, spans, and their timelines.
  • Works with various storage options, including Elasticsearch and others.
  • Easily connects with the OpenTelemetry Collector.

With Jaeger, you can gain a clear understanding.

  • How a user request travels across various services.
  • Which part of the system is taking more time?
  • Where errors are happening.
  • And how can you reduce delays (latency) to make your system faster?

It’s a great tool for debugging and improving performance in complex systems.

What You’ll See in Jaeger UI

Once you connect Jaeger to your system, it shows you a full trace of how a request flows, step by step. You can see.

  • A timeline of the request starting from the browser, moving to your API, and then reaching the database.
  • How long does each part of the request take, and how are different steps connected (parent-child structure)?
  • Practical details, such as the HTTP method, URL, and response status code.
  • The actual SQL query is being run from Entity Framework Core (EF Core).
  • Exceptions and error messages are captured as part of the trace.
  • Extra information like tags, logs, and attributes (e.g., user.id, environment, region, etc.).

All this makes it very easy to identify slow parts, fix bugs, or understand failures in complex systems that involve multiple services.

Where is Telemetry Data Stored?

Many people think that OpenTelemetry stores traces in the same SQL Server or Oracle database used by your app, but that’s not true.

By default, Jaeger saves trace data either in memory (which is temporary) or on the local disk using Badger; both are suitable for testing, but not for production.

For production environments, you should set up one of the supported storage systems.

Supported storage backends.

  • Elasticsearch: Most popular, good for searching and scaling
  • Apache Cassandra: Good for handling large amounts of data with horizontal scaling
  • Google Cloud Trace / AWS X-Ray: Great if you're using cloud platforms
  • Kafka + Elasticsearch: Helps buffer and process large trace data smoothly
  • ClickHouse / PostgreSQL: Available via community plugins using OpenTelemetry Collector

You don’t configure this in your app’s database. Instead, you set it in the OpenTelemetry Collector or Jaeger settings. The right choice depends on your team’s infrastructure, data size, and how you plan to search or analyse the trace data.

Securing Jaeger in Production

By default, Jaeger’s web UI is open to everyone. There is no login, no protection, which is risky if you’re running it in a real environment (like on the cloud or an internal network). Therefore, it is essential to add security before going live.

Option 1. Use Basic Authentication with IIS

If you’re hosting Jaeger behind IIS, you can enable Basic Auth like this.

  • Host Jaeger on IIS using reverse proxy (e.g., Application Request Routing + URL Rewrite).
  • Enable Basic Authentication in IIS for the Jaeger app or site.
  • Create a local user or add .htpasswd-like authentication using Windows Users.
  • Add a rule to forward /jaeger to Jaeger’s backend (default port is 16686).
    <rule name="ReverseProxyToJaeger">
      <match url="^jaeger/(.*)" />
      <action type="Rewrite" url="http://localhost:16686/{R:1}" />
    </rule>

Now, whenever someone accesses http://localhost/jaeger, IIS will ask for a username/password. You can easily manage users via Windows Authentication or use the Basic Auth module with custom users.

Option 2. Use OAuth2 Proxy with SSO

For more advanced setups, you can use OAuth2 Proxy.

Here’s what to do?

  1. Deploy OAuth2 Proxy as a sidecar or service.
  2. Connect it to your company’s SSO provider (like Google, Azure Active Directory, GitHub, Octa, or any other).
  3. Configure Jaeger behind this proxy, so only logged-in users from your org can access it.

This setup provides enterprise-level access control, allowing only authorized employees to access the Jaeger UI.

Conclusion

With .NET and OpenTelemetry, it has become significantly easier to perform full-stack tracing. You can track everything, from what the user is doing in the browser to how your backend API is working and even how your SQL queries are performing.

All this information is connected into one smooth, complete trace, so you can see the full journey of a request.

Jaeger works like your control panel or dashboard. It shows you everything in one place.

  • Live view of how your system is behaving
  • Where exactly are things going wrong
  • Helps you confidently handle issues in your production environment

This makes it very simple to monitor, debug, and optimize your applications from the frontend to the backend to the database, all in one view.

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...