ASP.NET Core

ASP.NET Core

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, internet-connected apps.

...see more

The easiest and safest fix is to validate configuration values before Azure services are registered. This prevents accidental fallback authentication and gives clear feedback if something is missing.

Here’s a clean version of the solution:

public static IServiceCollection AddAzureResourceGraphClient(
    this IServiceCollection services,
    IConfiguration config)
{
    var connectionString = config["Authentication:AzureServiceAuthConnectionString"];

    if (string.IsNullOrWhiteSpace(connectionString))
        throw new InvalidOperationException(
            "Missing 'Authentication:AzureServiceAuthConnectionString' configuration."
        );

    services.AddSingleton(_ => new AzureServiceTokenProvider(connectionString));
    return services;
}

This small addition gives you:

✔ Clear error messages
✔ Consistent behavior between environments
✔ No more unexpected Azure calls during tests
✔ Easier debugging for teammates

For larger apps, you can also use strongly typed configuration + validation (IOptions<T>), which helps keep settings organized and ensures nothing slips through the cracks.

With this guard in place, your integration tests stay clean, predictable, and Azure-free unless you want them to involve Azure.

...see more

Most Azure SDK components rely on configuration values to know how to authenticate. For example:

new AzureServiceTokenProvider(
    config["Authentication:AzureServiceAuthConnectionString"]
);
 

If this key is missing, the Azure SDK does not stop. Instead, it thinks:
“I’ll figure this out myself!”

And then it tries fallback authentication options, such as:

  • Developer login credentials
  • Azure CLI authentication
  • Managed Identity lookups
  • Subscription scans

These attempts fail instantly inside a local test environment, leading to confusing “AccessDenied” messages.
The surprising part?
Your project may work fine during normal execution—but your API project or test project may simply be missing the same setting.

This tiny configuration mismatch means:

  • Unit tests succeed
  • API runs fine locally
  • Integration tests fail dramatically

Once you understand this, the solution becomes much clearer.

...see more

Running integration tests in ASP.NET Core feels simple—until your tests start calling Azure without permission. This usually happens when you use WebApplicationFactory<T> to spin up a real application host. The test doesn’t run only your code; it runs your entire application startup pipeline.
That includes:

  • Configuration loading
  • Dependency injection setup
  • Background services
  • Azure clients and authentication providers

If your app registers Azure services during startup, they will also start up during your tests. And if the environment lacks proper credentials (which test environments usually do), Azure returns errors like:

  • AccessDenied
  • Forbidden

This can be confusing because unit tests work fine. But integration tests behave differently because they load real startup logic.
The issue isn’t Azure being difficult—it's your tests running more than you expect.

Understanding this is the first step to diagnosing configuration problems before Azure becomes part of your test run unintentionally.

...see more

Have you ever run an ASP.NET Core integration test and suddenly been greeted by an unexpected Azure “Access Denied” error? Even though your application runs perfectly fine everywhere else? This is a common but often confusing situation in multi-project .NET solutions. The short version: your tests might be accidentally triggering Azure authentication without you realizing it.

This Parent Snipp introduces the full problem and provides a quick overview of the three child Snipps that break down the issue step by step:

  • Snipp 1 – The Issue:
    Integration tests using WebApplicationFactory<T> don’t just test your code—they spin up your entire application. That means all Azure clients and authentication logic also start running. If your test environment lacks proper credentials, Azure responds with errors that seem unrelated to your actual test.

  • Snipp 2 – The Cause:
    The root cause is often a missing configuration value, such as an Azure authentication connection string. When this value is missing, Azure SDK components fall back to default authentication behavior. This fallback usually fails during tests, leading to confusing error messages that hide the real problem.

  • Snipp 3 – The Resolution:
    The recommended fix is to add safe configuration validation during service registration. By checking that required settings exist before creating Azure clients, you prevent fallback authentication and surface clear, friendly error messages. This leads to predictable tests and easier debugging.

Together, these Snipps give you a practical roadmap for diagnosing and fixing Azure authentication problems in ASP.NET Core integration tests. If you’re building APIs, background workers, or shared libraries, these tips will help you keep your testing environment clean and Azure-free—unless you want it to talk to Azure.

...see more

When you run an ASP.NET Core API from the command line, it will not use the port defined in launchSettings.json. This often surprises developers, but it is normal behavior.
The reason is simple: launchSettings.json is only used by Visual Studio or other IDEs during debugging.
To make your app listen on a specific port when running with dotnet run or dotnet MyApi.dll, you must configure the port using runtime options such as command-line arguments, environment variables, or appsettings.json.

Key Points

  • launchSettings.json does not apply when starting the app from the console.
  • Use dotnet run --urls "http://localhost:5050" to force a port.
  • Or set an environment variable:
    ASPNETCORE_URLS=http://localhost:5050
  • For a permanent app-level setting, use appsettings.json to define Kestrel endpoints.
  • Use http://0.0.0.0:5050 if running inside Docker or WSL.
...see more

When creating API endpoints in ASP.NET Core, you often need to ensure only authenticated users can access certain actions.
The [Authorize] attribute makes this easy — it automatically blocks unauthenticated requests.

Sometimes, you also load the current user from a database or a user service. In this case, it’s a good practice to add a null check as an extra safety step, even if [Authorize] is already applied.

Example

[Authorize]
[HttpPost("DoSomething")]
public async Task<IActionResult> DoSomething(RequestModel request)
{
    var user = await userService.GetContextUserAsync();

    if (user == null)
    {
        // Safety check in case the user is authenticated but not found in the database
        return Unauthorized("User not found.");
    }

    // Continue with the action
    return Ok("Action completed successfully.");
}

Key Ideas

  • [Authorize] ensures only authenticated users reach your action.
  • If your app looks up users in a database, add an extra if (user == null) check.
  • This prevents errors when tokens are valid but the user record no longer exists.

This pattern keeps your API safe, clean, and reliable.

...see more

To make your ASP.NET Core services easy to test and maintain, follow this proven pattern. The example below demonstrates how to register a service and configure an HttpClient with custom handlers, while keeping the design flexible for unit testing.

1. Register your service separately

Register your service interface and implementation as a singleton (or other lifetime as needed). This keeps the service replaceable in tests:

services.AddSingleton<IMyService, MyService>();

Tip: Use TryAdd for safe registration in reusable code

If your registration code is part of a shared library or package, use TryAdd to avoid overriding existing registrations accidentally:

services.TryAddSingleton<IMyService, MyService>();

2. Configure an HttpClient with handlers

Use a named HttpClient to add retry and logging handlers. These handlers improve reliability and diagnostics:

services.AddHttpClient(nameof(MyService))
    .AddHttpMessageHandler(s => new RetryHandler(s))
    .AddHttpMessageHandler(s => new LoggingHandler(s));

3. Add memory caching safely

You can call AddMemoryCache() without worry — it internally prevents duplicates:

services.AddMemoryCache();

Full Sample Method:

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddMyClientServices(this IServiceCollection services)
    {
        ArgumentNullException.ThrowIfNull(services);

        services.AddMemoryCache();

        services.TryAddSingleton<IMyService, MyService>();

        services.AddHttpClient(nameof(MyService))
            .AddHttpMessageHandler(s => new RetryHandler(s))
            .AddHttpMessageHandler(s => new LoggingHandler(s));

        return services;
    }
}

Why This Matters

  • Separation of concerns makes your code easier to test.
  • Named HttpClient with handlers improves reliability and debugging.
  • TryAdd keeps your library safe and reusable.
  • Memory cache registration is simple and safe.

Using this approach ensures your ASP.NET Core apps are easier to maintain, test, and extend.

...see more

It’s best practice to tailor logging levels per environment (Development, Staging, Production) by using environment-specific configuration files like appsettings.Development.json or appsettings.Production.json.

Example for Development (verbose logging):

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Information",
      "System": "Warning",
      "YourAppNamespace": "Trace"
    }
  }
}

Example for Production (concise logging):

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning",
      "YourAppNamespace": "Information"
    }
  }
}

By adjusting log levels per environment, you can capture detailed diagnostics during development while reducing noise and performance impact in production.

...see more

ASP.NET Core allows you to customize logging behavior per provider, such as Console or Application Insights. This is useful when you want different verbosity or volume controls depending on the sink.

Example:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning",
      "YourAppNamespace": "Trace"
    },
    "Console": {
      "LogLevel": {
        "Default": "Information",
        "YourAppNamespace": "Debug"
      }
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Error"
      }
    }
  }
}
  • Console logs are more verbose for development and debugging (Information and Debug).
  • Application Insights only logs errors to reduce telemetry volume and cost.

Use per-provider overrides when you want finer control over logging destinations.

...see more

In ASP.NET Core, you can configure logging levels to control the verbosity of logs across your application and third-party frameworks.

A common pattern is to set a default minimum log level (e.g., Warning) and enable verbose logging (Trace) only for your own application namespace.

Example configuration in appsettings.json or an environment-specific file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning",
      "YourAppNamespace": "Trace"
    }
  }
}
  • "Default": "Warning" sets a baseline for all logs.
  • "Microsoft" and "System" are explicitly set to Warning to reduce noise from framework logs.
  • "YourAppNamespace": "Trace" enables detailed logging for your application code.

This ensures your app logs detailed information while keeping system logs concise and manageable.

...see more

Logging is a critical aspect of application monitoring and diagnostics. ASP.NET Core provides flexible logging configuration options to help you balance verbosity and noise across different environments and providers.

This series covers best practices for configuring logging levels, including:

  • Setting baseline and application-specific log levels
  • Customizing logging behavior per provider (e.g., Console, Application Insights)
  • Tailoring logging configurations for different environments (Development, Production, etc.)

Explore the related Snipps below to implement a robust, maintainable logging strategy in your ASP.NET Core applications.

...see more

DelegatingHandlers can be tested in isolation:

  1. Mock the Inner Handler:

    var mockHandler = new Mock<HttpMessageHandler>();
    mockHandler.Protected()
               .Setup<Task<HttpResponseMessage>>("SendAsync", ...)
               .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));
  2. Inject into DelegatingHandler:

    var customHandler = new CustomHandler
    {
        InnerHandler = mockHandler.Object
    };
  3. Create HttpClient:

    var client = new HttpClient(customHandler);

This approach allows for unit testing the DelegatingHandler's logic without making actual HTTP calls.

...see more

Multiple DelegatingHandlers can be chained to create a pipeline:

services.AddTransient<LoggingHandler>();
services.AddTransient<AuthenticationHandler>();
services.AddHttpClient("ChainedClient")
        .AddHttpMessageHandler<LoggingHandler>()
        .AddHttpMessageHandler<AuthenticationHandler>();

In this setup, LoggingHandler processes the request first, followed by AuthenticationHandler. The order of registration determines the sequence of execution.

...see more

To create a custom DelegatingHandler:

  1. Inherit from DelegatingHandler:

    public class CustomHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Pre-processing logic
            var response = await base.SendAsync(request, cancellationToken);
            // Post-processing logic
            return response;
        }
    }
  2. Register the Handler:
    In ASP.NET Core, register the handler using IHttpClientFactory:

    services.AddTransient<CustomHandler>();
    services.AddHttpClient("NamedClient")
            .AddHttpMessageHandler<CustomHandler>();
...see more

Summary:
This video demonstrates how to generate a TreeView structure using data directly from a SQL Server database in an MVC 4 application. The example uses recursive methods to fetch hierarchical data from a parent-child table (such as a category structure). The TreeView is rendered using a combination of Razor and recursive HTML helpers.

Key Steps:

  • Create a SQL table with ID and ParentID fields.
  • Use Entity Framework to fetch data into a recursive model.
  • Write recursive logic in the controller to build the tree.
  • Use a partial view or helper method to render nested HTML in the view.

Best For:
Developers working with older ASP.NET MVC versions who need to generate TreeViews from database-driven content, particularly with dynamic data structures.

...see more

Summary:
This tutorial walks through building a TreeView in ASP.NET Core using ViewModel binding and JSON serialization. The TreeView is rendered on the client side using a simple recursive HTML structure. The backend constructs the hierarchy from a static or database source and passes it to the view. The data is structured using parent-child relationships, and the final JSON is passed to the view for rendering. No third-party libraries are used, making it a lightweight and transparent solution.

Key Steps:

  • Define a hierarchical ViewModel with recursive child collections.
  • Populate the ViewModel with data (manually or from a database).
  • Serialize the structure into JSON.
  • Render the TreeView in a Razor view using JavaScript.

Best For:
Developers using ASP.NET Core who want a lightweight, client-side rendered TreeView without relying on jQuery plugins or third-party UI components.

...see more

TreeView is a popular UI component used for displaying hierarchical data in a nested, expandable structure. In ASP.NET MVC and ASP.NET Core, creating a TreeView can enhance navigation, represent parent-child relationships (such as categories or folders), and improve user interaction with complex data structures.

This overview introduces how TreeViews are implemented in both ASP.NET MVC 4 and ASP.NET Core, using Razor views and model binding, and how data from a database can be dynamically rendered in a hierarchical format.

...see more

DelegatingHandler is a powerful mechanism in ASP.NET that enables developers to intercept and manipulate HTTP requests and responses. Functioning similarly to middleware, it allows for the implementation of cross-cutting concerns such as logging, authentication, and error handling in a modular and reusable manner.

Key Features:

  • Middleware-like Behavior: Processes HTTP requests and responses in a pipeline fashion.
  • Cross-Cutting Concerns: Ideal for tasks like logging, authentication, and error handling.
  • Reusability: Handlers can be reused across different HttpClient instances.
  • Testability: Facilitates unit testing by isolating concerns

 

Common Use Cases for DelegatingHandler

DelegatingHandler is versatile and can be employed for various purposes:

  • Authentication: Attach tokens or API keys to outgoing requests.
  • Logging: Log request and response details for monitoring and debugging.
  • Error Handling: Implement retry policies or handle specific HTTP status codes.
  • Caching: Cache responses to reduce redundant network calls.
  • Header Manipulation: Add or modify headers in requests or responses.

 

DelegatingHandler vs. Middleware

While both DelegatingHandler and middleware can process HTTP requests and responses, they serve different purposes:

  • Middleware: Operates on incoming HTTP requests to the server.
  • DelegatingHandler: Operates on outgoing HTTP requests from HttpClient.

Use middleware for server-side concerns and DelegatingHandler for client-side HTTP request processing.

...see more

ASP.NET Core provides robust support for making outbound HTTP requests using HttpClient, often via the IHttpClientFactory. This section covers advanced features for managing these requests, including the use of DelegatingHandler for building custom request/response pipelines. These handlers enable cross-cutting concerns like logging, authentication, and retries in a modular and testable way.

This section includes:

  • Introduction to DelegatingHandler
  • Creating and registering custom handlers
  • Chaining multiple handlers
  • Practical use cases
  • Differences between DelegatingHandler and middleware
  • Testing strategies for handlers
...see more

Kubernetes ist in der Cloud-Welt allgegenwärtig; nahezu alle Public-Cloud-Anbieter offerieren Kubernetes als Managed Service oder nutzen es intern für ihre PaaS- und Serverless-Dienste. Auch in lokalen Rechenzentren wird Kubernetes häufig eingesetzt und entfaltet dort seine Stärken als Plattform. Obwohl sich die verschiedenen Kubernetes-Distributionen und Managed Services in technischen Details wie Installation und Integration von Netzwerk- und Speicherressourcen unterscheiden, bleibt die Plattform für Anwendungen weitgehend einheitlich. Mit minimalen Konfigurationsanpassungen können Applikationen sowohl in der Cloud als auch in On-Premises-Umgebungen nahtlos betrieben werden.

Quelle: Kurs auf Kubernetes! (dotnetpro.de)

...see more

ASP.NET Core provides a rich set of tools for handling HTTP communication—both inbound and outbound. This root Snipp focuses on outbound HTTP requests using HttpClient, IHttpClientFactory, DelegatingHandler, and related patterns. These features are critical for building resilient services that interact with external APIs and microservices.

Topics covered under this root:

  • Configuring and using HttpClient with IHttpClientFactory
  • Creating and chaining DelegatingHandlers
  • Implementing cross-cutting concerns (e.g., logging, retries, authentication)
  • Best practices for performance, resilience, and testing
  • Distinction between client-side handlers and server-side middleware

This section is essential for developers building cloud-native apps, microservices, or any service that consumes external APIs.

...see more

Inject Configuration

To inject configuration settings in your ASP.NET Core application, use Microsoft.Extensions.Configuration and inject IConfiguration into your page or component. Access configuration values using Configuration["KeyName"].

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<!-- Access configuration value -->
@Configuration["ApplicationInsights:InstrumentationKey"]

Options Pattern

For more structured configuration management, use the options pattern with Microsoft.Extensions.Options. Inject IOptionsMonitor<TOptions> with @inject and access configuration values through OptionsAccessor.Value.PropertyName.

@using Microsoft.Extensions.Options
@inject IOptionsMonitor<ApplicationInsightsOptions> ApplicationInsightsOptionsAccessor

<!-- Access configuration value -->
var instrumentationKey = ApplicationInsightsOptionsAccessor.Value.InstrumentationKey;

For detailed information, refer to the ASP.NET Core documentation on configuration options.

...see more

Razor is a concise markup language that integrates server-side code (C# or VB) into ASP.NET web pages seamlessly. It simplifies web development by blending code and HTML, enhancing productivity and maintainability.

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<h1>@ViewData["Title"]</h1>
<p>Welcome to my ASP.NET Core Razor Pages!</p>

In this code snippet, the @page directive specifies the page, @model defines the page's model, and @ViewData displays dynamic data within the Razor Page markup.

Resources

...see more

Razor Syntax allows you to embed code (C#) into page views through the use of a few keywords, and then have the C# code be processed and converted at runtime to HTML.

...see more

Here are six different ways to run your ASP.NET Core web application:

  1. Visual Studio F5: Simply press F5 in Visual Studio to run your application.
  2. Command Line (dotnet run): Open a terminal and run dotnet run in your project directory.
  3. Publish and Run: Use dotnet publish to create a publish folder, then navigate to bin\{...}\publish and run dotnet YourProject.dll.
  4. IIS: Host your application on IIS for production-level hosting.
  5. Linux Console: Run dotnet YourProject.dll on Linux from the console.
  6. Linux with Supervisor and Nginx: For robust production setups on Linux, use Supervisor to manage your application and Nginx as a reverse proxy.

For more detailed information, check out the guide on 6 different ways to run an asp.net core web application (secretGeek.net)

...see more

Before jumping to the solution, let's talk about use cases. Using both tokens and cookies is not a common use case, but it typically comes up when you have a SPA or pure API applications that also need to secure some non-SPA pure Web Browser end points that the server sends directly to the browser. If that content needs to be protected behind authentication you might need Cookie authentication, because you can't do Bearer Token authentication with plain HTML interfaces in the browser.

services.AddAuthentication(options =>
    {
        // custom scheme defined in .AddPolicyScheme() below
        options.DefaultScheme = "JWT_OR_COOKIE";
        options.DefaultChallengeScheme = "JWT_OR_COOKIE";
    })
    .AddCookie("Cookies", options =>
    {
        options.LoginPath = "/login";
        options.ExpireTimeSpan = TimeSpan.FromDays(1);
    })
    .AddJwtBearer("Bearer", options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = config.JwtToken.Issuer,
            ValidateAudience = true,
            ValidAudience = config.JwtToken.Audience,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.JwtToken.SigningKey))
        };
    })

Source: Combining Bearer Token and Cookie Authentication in ASP.NET - Rick Strahl's Web Log (west-wind.com)

Add to Set
  • .NET
  • Agile
  • AI
  • ASP.NET Core
  • Azure
  • C#
  • Cloud Computing
  • CSS
  • EF Core
  • HTML
  • JavaScript
  • Microsoft Entra
  • PowerShell
  • Quotes
  • React
  • Security
  • Software Development
  • SQL
  • Technology
  • Testing
  • Visual Studio
  • Windows
Actions
 
Sets