开发者
Sealed Isn't a Restriction, It's a Promise
Leaving a class open to inheritance is a design decision, not a default you can ignore. The core idea An unsealed class is a promise: every virtual member can be overridden without breaking what the class guarantees. Most classes never meant to make that promise. They're just unsealed by default, because that's what class gives you unless you say otherwise. Common mistake: treating sealed as "I don't want to think about subclassing" rather than "this type's invariants would break if someone could." One override breaks the promise Here's the promise, a BankAccount that refuses to go negative: public class BankAccount { public decimal Balance { get ; protected set ; } public virtual void Withdraw ( decimal amount ) { if ( amount > Balance ) throw new InvalidOperationException (); Balance -= amount ; } } And here's the override that breaks it: public class RiskyAccount : BankAccount { public override void Withdraw ( decimal amount ) { Balance -= amount ; // no check } } Nothing here is exotic. It compiles cleanly, and RiskyAccount is a perfectly legal BankAccount as far as the type system is concerned. Open one with a balance of 100 and withdraw 500: BankAccount account = new RiskyAccount ( 100m ); account . Withdraw ( 500m ); Console . WriteLine ( $"Balance: { account . Balance : F2 } " ); Real dotnet run output: Balance: -400.00 The check on the left never ran. virtual was an open invitation, and RiskyAccount took it. Sealing turns a silent bug into a compile error Without sealed , the code above compiles and produces a wrong answer at runtime; nothing points you at the problem until it's already in production. With sealed , the same mistake becomes something the compiler catches before the code ever runs: public sealed class BankAccount { public decimal Balance { get ; protected set ; } public void Withdraw ( decimal amount ) { if ( amount > Balance ) throw new InvalidOperationException (); Balance -= amount ; } } public class RiskyAccount : BankAccount { } // error
AI 资讯
Retries Are Not a Recovery Strategy
A retry answers a narrow question: might the same operation succeed if I attempt it again? Recovery has a harder job. It must bring the original business operation to a known, valid outcome after something went wrong. Getting there may require another attempt, a status lookup, resuming from persisted state, or compensation. If the system cannot resolve the operation safely, it must hand it to a person. This difference matters as soon as an AI workflow does more than return text. If it retrieves data, calls tools, writes state, or continues after the HTTP request ends, adding three retries around the workflow is not a recovery design. It is three more chances to spend money, repeat a side effect, or lose track of what already happened. A retry repeats an attempt Suppose a support feature performs this workflow: load the ticket and approved policy -> generate a reply -> validate the reply -> save it as a draft The policy read returns 503 Service Unavailable with an applicable Retry-After response, and the dependency contract classifies it as transient. No application business state changed, and the request still has time left. A delayed retry may be reasonable. Now suppose the draft save times out after the request reached the database. The caller cannot tell whether the write committed. Repeating the complete workflow creates a new model response and may save a second draft. Retrying only the write is safe when the write is naturally idempotent, or when the boundary can recognize the retry as the same logical operation. Otherwise, the second attempt may create another draft. Both failures may appear as a timeout or dependency exception in application code. They do not have the same effect. What happened What is known Suitable response A transient policy read failed before returning data No application business state changed Retry the read within its budget The model endpoint rejected an invalid request The same request will fail again Stop and fix the request or cont
AI 资讯
Should Your Prompt Store Pick Your Model
Langfuse with Microsoft.Extensions.AI has an appealing story: update prompts without redeploying. A prompt fetches its config blob—model, tokens, temperature—which the code passes straight to the LLM. It works. But it puts a boundary in what I'd suggest might be better placed elsewhere — and moving it is a small enough change to be worth exploring. This post is about where to move that line in a .NET codebase using Microsoft.Extensions.AI against OpenAI or Azure OpenAI, with Langfuse as the source of prompts. What the current setup buys you Let me be fair to it first, because the coupling is a deliberate design, not an accident. Langfuse's prompt config is an optional JSON object versioned alongside the prompt. That means someone can open the Langfuse UI, change the model or a parameter, and ship it — no code change, no redeploy. Combined with labels (pointers to specific versions that your code references), a rollback is just moving the production label back to an earlier version. For prompt content iteration, that story is genuinely good, and there is a real audience of people who want model config coupled to prompt versions more tightly so each version is fully self-describing and reproducible. So this is a trade-off, not a bug. The question is whether the thing you are optimizing for — non-engineers tuning prompts without a deploy — is worth what the coupling costs. Why I think this deserves consideration Three points stand out. It is an untyped blob feeding provider selection. The Langfuse config is arbitrary JSON without schema enforcement. On the other end, whatever LLM plumbing you use will treat that model string as authoritative. A missing key, a stray max_tokens , or a gpt4o typo might not fail at build time or deploy time — it could fail on a live request, or silently do something unintended. You have a loosely-typed value driving an infrastructure decision, and the mistake may not surface until traffic hits it. It conflates two change lifecycles with di
AI 资讯
System Design: Payment Processing System
System Design: Payment Processing System A capstone system design walkthrough — designing a payment processing system end to end — covering the core domain model, the ledger as the system's source of truth, idempotency and exactly-once-effect guarantees, integrating with external payment gateways and card networks, handling asynchronous webhooks, reconciliation, fraud and risk checks, and the specific correctness and compliance demands that make payments a uniquely unforgiving system design problem. Table of Contents Introduction Why Payment Systems Are a Different Kind of Hard The Core Domain Model The Ledger: Double-Entry Bookkeeping as the Source of Truth Idempotency: The Single Most Important Property Integrating with Payment Gateways and Card Networks The Payment State Machine Webhooks: Handling Asynchronous Gateway Callbacks The Saga: Coordinating Payment Across Multiple Services Reconciliation Fraud and Risk Checks Data Security and Compliance Consistency, Availability, and the CAP Trade-off for Money Scaling the System Observability for a Payment System Common Pitfalls Quick Reference Table Conclusion Introduction A payment processing system takes the general system design vocabulary covered in this series' System Design guide — databases, caching, queues, load balancing — and applies it to a domain where the ordinary consequences of a bug are dramatically higher: a double-charged customer, a lost payment, or a corrupted ledger isn't a degraded user experience, it's real money moved incorrectly, sometimes irreversibly. This guide walks through designing such a system end to end, drawing directly on this series' DDD, Event-Driven Architecture, Database Migrations, and Secret Management guides, each of which turns out to be load-bearing infrastructure for getting payments right rather than optional architectural polish. Client → Payment API → [validate, risk-check] → Payment Gateway (Stripe/Adyen/etc.) → Card Network → Bank ↓ ↓ (async webhook) Ledger (source o
AI 资讯
NET Framework Essentials: Web Development Simplified
Your backend framework will outlive your current team. Choose one that the next team can still navigate — here's why .NET has been that framework for Netflix, GitHub, and Stack Overflow for over two decades. Summary Twenty-three years. That's how long .NET has been running in production. Most frameworks from that era got abandoned, forked beyond recognition, or replaced entirely — .NET kept showing up. Netflix still uses it. GitHub uses it. Stack Overflow, which has probably saved more developer careers than any single resource on the internet, runs on ASP.NET. None of these teams are using it out of inertia. They're using it because it works under conditions that expose every weakness in a poorly designed system. This article gets into how .NET actually works, what it gives teams day-to-day, and whether it makes sense for what you're building now. Key Takeaways: One codebase, five platforms — Windows, macOS, Linux, Android, iOS. No rewrites, no platform-specific forks. Three languages, one project — C#, F#, and Visual Basic coexist without forcing a rewrite. The performance tooling ships with it — JIT compiler, AOT compiler, CLR memory management, Garbage Collector. All out of the box. Why Is .NET Still Around? Honestly, this question is worth sitting with for a second — because in software, most things don't survive twenty years. They solve the problem of the moment, get widely adopted before anyone finds the sharp edges, and then get quietly replaced when something newer comes along and the migration pain seems worth it. .NET didn't go that way. Some of that is Microsoft backing — resources, long-term support commitments, a developer community that doesn't dissolve when priorities shift. But backing alone doesn't explain it. Plenty of well-resourced frameworks have died. What actually kept .NET alive is that the foundational architecture held up. The cross-platform capability wasn't duct-taped on in 2020 because everyone suddenly cared about Linux. It was in the
AI 资讯
EF Core bugs that look like correct code
Most EF Core bugs I've seen in production aren't from bad code. They're from code that looks right. It compiles, it passes review, it works fine locally against a database with twelve rows in it. Then it hits a table with five thousand rows, or a second replica, or a request that gets cancelled halfway through, and it falls over in a way nobody wrote a test for. None of the mistakes below are exotic. They're the default behavior of EF Core when you don't opt out of it, or the default behavior of a deployment when nobody thought about what "five pods start at the same time" actually means. Here's the setup I use and the list of ways it goes wrong if you skip a step. The entity namespace Sample.Domain.Posts ; public sealed class Post { public Guid Id { get ; private set ; } = Guid . CreateVersion7 (); // sequential → index-friendly public required string Title { get ; set ; } public required string Slug { get ; init ; } public string Body { get ; set ; } = string . Empty ; public DateTimeOffset ? PublishedAt { get ; private set ; } public Guid AuthorId { get ; init ; } public uint RowVersion { get ; set ; } // optimistic concurrency token public void Publish ( TimeProvider clock ) { if ( PublishedAt is not null ) throw new DomainException ( "Post is already published." ); PublishedAt = clock . GetUtcNow (); } } Two things here that are easy to skip and annoying to retrofit later. Timestamps are stored as UTC ( DateTimeOffset ), rendered in the user's timezone only at the edge — I do the same thing on ProcessHub, storing everything UTC and rendering in Asia/Tehran, because "what timezone is this in" is a much worse question to answer after the data already exists in three different formats. Second: the clock comes in as TimeProvider , not a call to DateTime.UtcNow buried inside the method. It's a small thing, but it's the difference between a test that can assert "publishing sets the timestamp to exactly this value" and a test that has to accept "sometime around now."
AI 资讯
.NET 10 NU1015: Fix PackageReference Without Version Restore Failures
.NET 10 NU1015 turns a PackageReference without a version into a restore error. I like the stricter default because an unbounded direct dependency can quietly resolve the lowest package version. The catch is that versionless XML is also the correct shape for NuGet Central Package Management (CPM). A mechanical “add Version everywhere” repair can undo the policy your repository intended to enforce. I use a simple split: first decide who owns the version, then make restore prove the answer. Why .NET 10 NU1015 stops the build Before .NET 10, NuGet reported NU1604 when a direct reference had no inclusive lower bound. Restore could continue and select the lowest version available from the configured sources. Starting with .NET 10, the same mistake produces NU1015 and restore fails. Microsoft documents this as a stable behavioral change in the .NET 10 compatibility guidance . Here is the ambiguous project entry: <ItemGroup> <PackageReference Include= "Demo.Greeting" /> </ItemGroup> If this is a normal direct reference, the project is missing its version. If CPM is active, the project is correct and the version should live elsewhere. The NU1015 diagnostic reference calls out a common failure mode: a project that expected CPM was copied into a location where CPM is disabled or its props file is no longer discovered. That distinction matters more than silencing the error. It tells me whether the project file or the repository-level package policy is broken. The timing can be misleading. An SDK upgrade may expose an old direct reference that had always relied on lowest-version resolution, while a repository move may break a previously valid CPM import. I inspect the failing project's evaluated inputs, nearby props files, and recent path changes before editing package metadata. That keeps a restore migration from turning into an accidental package-management migration. Fix the owner, not only the XML For a direct reference, I add an explicit version: <PackageReference Include=
AI 资讯
.NET 10 JSON Console Logging: Stop Parsing State.Message
The .NET 10 JSON console logging change is small enough to miss during an upgrade: the formatted message still exists, but a typical record no longer duplicates it at State.Message . A collector, script, or snapshot test that reads only that nested property can start returning null while the application continues logging normally. I treat console JSON as a schema whenever another process parses it. That means a runtime upgrade deserves a contract test, not just a visual check in a terminal. The practical fix is to read the top-level Message , keep State for structured values, and retain a narrow fallback for older records. Why .NET 10 JSON console logging breaks nested-message parsers Before .NET 10, a normal AddJsonConsole record commonly repeated the rendered text: { "Message" : "Order 42 moved to ready." , "State" : { "Message" : "Order 42 moved to ready." , "OrderId" : 42 , "Status" : "ready" , "{OriginalFormat}" : "Order {OrderId} moved to {Status}." } } In .NET 10, the typical shape keeps one rendered message at the top level: { "Message" : "Order 42 moved to ready." , "State" : { "OrderId" : 42 , "Status" : "ready" , "{OriginalFormat}" : "Order {OrderId} moved to {Status}." } } Microsoft documents this as a behavioral breaking change and recommends that parsers use the top-level property. The official compatibility note also gives an essential caveat: State.Message may still appear when its content differs from the top-level value. I therefore do not reject a record merely because both properties exist. This is not a loss of structured logging data. OrderId , Status , and {OriginalFormat} remain useful fields inside State . The part that changed is where a consumer should get the rendered sentence. Prefer the top-level Message and keep State structured A legacy-only extractor is brittle because it assumes the duplicate is the contract: static string ? ReadLegacyOnly ( JsonElement root ) => root . TryGetProperty ( "State" , out var state ) && state . TryGetPro
AI 资讯
A Reason Code Without a Source Is Half a Diagnostic
A failure message can be technically correct and still be frustratingly incomplete. Consider a timeout. It tells us something important about the failure mechanism, but not which operation encountered it. Adding the complete request target might answer that question, yet it can also expose identifiers, query parameters, access material, or other data that never belonged in a broadly visible diagnostic record. A safer middle ground is to give failures two separate coordinates: a reason code that explains how the operation failed, and a bounded operation label that explains where it failed. That distinction makes diagnostics more useful without turning failure handling into an accidental data-exposure channel. A reason code is not a location Reason codes describe failure mechanics. Generic examples might include deadline , cancelled , unauthorised , or invalid_response . These codes are valuable because they let systems group similar outcomes. A dashboard can count deadline failures across operations, while application logic can decide whether a particular reason is retryable. What a reason code cannot reliably explain is the operation being attempted. A deadline during a summary read may require a different investigation from a deadline while assembling a detailed response. Combining both meanings into one free-form message makes failures harder to query and encourages presentation text to become an informal data model. Model the two coordinates separately A deliberately generic, invented C# model might look like this: public enum OperationArea { Summary , Detail , Archive } public sealed record FailureDetail ( string ReasonCode , OperationArea ? Area = null ); The reason remains suitable for classification. The operation label adds location without carrying an unrestricted request value. An enum is not the only option. A validated value object or centrally managed set of constants can work too. The important constraint is that labels come from a small, reviewed voca
AI 资讯
MCP C# SDK Hybrid Sessions: Serve Old and New Clients on One Endpoint
The MCP C# SDK hybrid sessions option solves an awkward upgrade boundary: some clients still use the 2025-11-25 initialize handshake and depend on sessions, while clients on 2026-07-28 expect every HTTP request to stand alone. I want both groups to reach one ASP.NET Core endpoint without making modern clients downgrade or stripping useful behavior from legacy clients. The stable C# SDK 2.2.0 release added exactly that path with HttpServerSessionMode.StatefulForInitializeClients . The release notes describe it as hybrid stateful/stateless serving, and the official session-mode guide spells out the per-request behavior. Why one global session switch fails The 2026-07-28 MCP revision removed the initialize handshake and Mcp-Session-Id from its wire format. Client identity, capabilities, and protocol version travel with each request instead. The final specification announcement explains why the core moved toward request/response statelessness. That creates a migration choice for an existing server. With HttpServerSessionMode.Stateful , initialize-era clients receive full sessions. A modern request is refused so a dual-path client can fall back to the older handshake. Compatibility is preserved, but the client does not use the new protocol natively. With HttpServerSessionMode.Stateless , every request is independent. That is the right default for servers that do not need session state, unsolicited notifications, resource subscriptions, or older server-to-client flows. It may be too abrupt when deployed clients still rely on those features. Hybrid mode makes the decision from the incoming request instead of applying one choice to the endpoint. Configure MCP C# SDK hybrid sessions The server configuration is deliberately small: builder . Services . AddMcpServer () . WithHttpTransport ( options => { options . SessionMode = HttpServerSessionMode . StatefulForInitializeClients ; }) . WithTools < DemoTools >(); app . MapMcp ( "/mcp" ); An initialize-era client sends an initial
AI 资讯
Implementing Feature Management in .NET: The Lazy Way
Microsoft did the hard work so you don't have to. The Microsoft.FeatureManagement library integrates directly with .NET's configuration and dependency injection systems, which means you can get feature flags working with minimal code and a solid foundation. For the full documentation, check out the Microsoft Feature Management documentation . Let's get this thing running. Installation Add the NuGet package to your project: dotnet add package Microsoft.FeatureManagement.AspNetCore That's it for dependencies. No magic rituals required. Configuration Register the feature management services in Program.cs : builder . Services . AddFeatureManagement (); By default, feature flags are read from the FeatureManagement section of your appsettings.json : { "FeatureManagement" : { "NewDashboard" : true , "ExperimentalSearch" : false } } Flag names are strings. Values are booleans. Simple. Checking a Flag in Code Inject IFeatureManager wherever you need to check a flag: public class DashboardController : Controller { private readonly IFeatureManager _featureManager ; public DashboardController ( IFeatureManager featureManager ) { _featureManager = featureManager ; } public async Task < IActionResult > Index () { if ( await _featureManager . IsEnabledAsync ( "NewDashboard" )) { return View ( "NewDashboard" ); } return View ( "OldDashboard" ); } } That's the whole pattern. Inject. Check. Branch. Repeat. Using Feature Filters Boolean flags are useful, but sometimes you need something a little more sophisticated. The library supports feature filters for things like: Percentage rollouts Time windows User targeting For example, you can enable a feature for a percentage of requests: { "FeatureManagement" : { "BetaFeature" : { "EnabledFor" : [ { "Name" : "Percentage" , "Parameters" : { "Value" : 20 } } ] } } } This enables BetaFeature for 20% of requests. The library handles the sampling. You handle the business logic. Everybody wins. Razor Tag Helpers Building a Razor-based UI? The lib
开源项目
.NET 10 dotnet tool exec: Pin the Version and Feed in CI
A CI step that says dotnet tool exec Some.Tool looks isolated, but it is not fully reproducible. Without a version, the command can resolve the latest package from the configured feeds. Machine-level NuGet settings can also change which feeds participate. I use .NET 10 dotnet tool exec with an exact @version and an explicit feed policy when I want one-shot tooling without a global install or a committed tool manifest. The command is stable from the .NET 10.0.100 SDK onward. Microsoft describes it as a temporary invocation: the package is downloaded to the NuGet cache, executed, and left out of PATH . That is convenient for CI, but temporary installation does not automatically mean deterministic selection. Why .NET 10 dotnet tool exec can drift The official command reference documents three useful selection modes: Some.Tool can resolve the latest version when no local manifest supplies one. Some.Tool@2.* stays on a major version, but still floats within that range. Some.Tool@2.4.1 requests one exact package version. For CI, I prefer the third form. A new tool release should arrive through a reviewed change, not because the next clean runner happened to restore later. The feed is a separate input. --add-source adds another source, and NuGet can query feeds in parallel. If the same package and version exists on more than one feed, the fastest response can win. That may be acceptable for interactive experimentation. It is a poor default for a build gate. .NET 10 is currently an active LTS channel . I still pin the SDK used by CI as well, because a package pin controls the tool package, not the CLI that resolves and launches it. Pin the version and feed together For a repository policy, I give dotnet tool exec a checked-in NuGet.Config . This sample uses a generated local feed, so it needs no credentials or external package call: <?xml version="1.0" encoding="utf-8"?> <configuration> <config> <add key= "globalPackagesFolder" value= "./artifacts/global-packages" /> </conf
AI 资讯
Design Patterns: Reusable Solutions to Recurring Problems
Design Patterns: Reusable Solutions to Recurring Problems A practical guide to classic design patterns in C#/.NET — Factory, Singleton, Repository, Strategy, and Mediator — covering what problem each one actually solves, working implementations, common .NET-specific variations, and honest guidance on when each pattern earns its complexity versus when it's unnecessary ceremony. Table of Contents Introduction Factory Pattern Singleton Pattern Repository Pattern Strategy Pattern Mediator Pattern How These Patterns Combine in Practice Patterns vs. Over-Engineering Common Pitfalls Quick Reference Table Conclusion Introduction Design patterns are named, reusable solutions to problems that recur often enough across software projects that giving them a shared name and shape is genuinely useful — not because the specific code is copy-pasteable, but because the name lets developers communicate a design intent quickly ("just make it a Strategy") instead of re-explaining the same structural idea from scratch every time. This guide covers five of the most commonly used patterns in .NET codebases, with working C# examples, and — consistent with this series' recurring theme — honest guidance on when each pattern is solving a genuine problem versus adding structure a simpler solution wouldn't need. // A pattern name compresses a whole design conversation into one word "Just inject an IPaymentStrategy and pick the implementation based on the payment method" // ← Strategy "Wrap the whole multi-step checkout process behind a single mediator call" // ← Mediator 1. Factory Pattern The problem: object creation logic that doesn't belong at the call site // ❌ The caller needs to know about every concrete shipping provider and how to construct each one IShippingProvider provider = order . Region switch { "US" => new UpsShippingProvider ( apiKey , region ), "EU" => new DhlShippingProvider ( apiKey , endpoint ), "APAC" => new FedExShippingProvider ( apiKey , credentials ), _ => throw new NotS
AI 资讯
xUnit 4 ParallelMode.All: Protect Shared State from Test Races
xUnit 4.0.0 makes full test-case parallelization an explicit option. That is useful, but xUnit 4 ParallelMode.All changes a quiet assumption in many suites: tests in the same class, including separate rows of one theory, may now overlap. A static fake, shared fixture, temporary file, or database record that was safe under collection-level parallelism can become a race. I treat this as an isolation change, not a speed switch. Before enabling it across a suite, I want a deterministic failure that proves the risk and a deterministic check for each guardrail. What xUnit 4 ParallelMode.All changes The xUnit.net v3 4.0.0 release notes describe full test-case parallelization as a new feature. The default is still ParallelMode.Collections , so upgrading does not silently enable the broader mode. I have to opt in at the assembly level: using Xunit.Sdk ; using Xunit.v3 ; [ assembly : Parallelization ( Mode = ParallelMode . All , MaxThreads = 2 , Algorithm = ParallelAlgorithm . Conservative )] With Collections , tests within a collection are serialized. With All , every test case is eligible to run beside every other test case. That includes two cases from the same class and two pre-enumerated rows from the same theory. The official parallel test execution guide documents the modes, algorithms, and available opt-out scopes. I set MaxThreads = 2 in the sample so the scheduling condition is easy to inspect. It is a demonstration setting, not a recommendation for CI. The right value depends on available CPU, memory, and the external systems touched by the tests. Before changing the mode, I scan for mutable static fields, IClassFixture and ICollectionFixture implementations, fixed file names, environment-variable changes, test servers bound to fixed ports, and records addressed by shared IDs. I also check theory data sources for objects that rows can mutate. That inventory tells me whether the resource should become concurrency-safe, receive a unique per-test identity, or stay beh
AI 资讯
ASP.NET Core 10 Authentication Metrics: Distinguish No Result from Failure
When every unauthorized request becomes the same dashboard line, diagnosis turns into guessing. ASP.NET Core 10 authentication metrics give me a better split: did the handler have nothing to authenticate, reject supplied credentials, or accept them? That distinction matters because a client deployment that drops credentials needs a different response from a surge of malformed or expired credentials. ASP.NET Core 10 added built-in authentication and authorization instruments to System.Diagnostics.Metrics . I can collect them without rewriting each handler, and I can lock their behavior into an offline test before wiring up a production exporter. Why one 401 hides two different problems A protected endpoint normally challenges an unauthenticated caller. The final status is 401 whether the caller sent nothing or the handler rejected what it received. The authentication duration histogram exposes the missing context through aspnetcore.authentication.result : Result What the handler reported A common interpretation none No authentication result No applicable credentials were available failure Authentication failed Supplied credentials were rejected or processing failed success A principal was created Authentication completed successfully _OTHER Another framework result Preserve it as an explicit catch-all none is a handler result, not a universal synonym for “missing Authorization header.” A policy scheme or custom handler can make a different choice. I verify the behavior of the schemes I actually deploy instead of building an alert from the label alone. Likewise, success means the handler produced an authentication ticket. Authorization can still deny that principal, so it does not promise a 2xx response. The separate aspnetcore.authentication.challenges counter answers another question: how often was a scheme challenged? Both a none result and a failure result can be followed by a challenge, so challenge count cannot replace the result split. A challenge is an authent
AI 资讯
ASP.NET Core Output Caching: How to Make Web APIs Faster in .NET
ASP.NET Core Output Caching: How to Make Web APIs Faster in .NET When an API receives the same request repeatedly, performing the same database query and rebuilding the same response every time can waste valuable resources. For example, imagine this endpoint: GET /api/products If thousands of users request the same product catalog, your application might repeatedly: HTTP Request ↓ Controller ↓ Database Query ↓ Business Logic ↓ JSON Response For data that doesn't change frequently, this can create unnecessary database load. ASP.NET Core provides Output Caching to help solve this problem. Instead of executing the complete request pipeline every time, the application can temporarily store the generated response and reuse it for subsequent requests. In this tutorial, we'll look at how Output Caching works, how to configure it, how to invalidate cached responses, and when you should avoid using it. What Is Output Caching? Output caching stores the generated response from an endpoint. For example: First request ↓ GET /api/products ↓ Execute controller ↓ Query database ↓ Generate response ↓ Store response in cache Later: Second request ↓ GET /api/products ↓ Cached response ↓ Return immediately The database doesn't need to be queried again while the cached response is valid. Output Caching vs Response Caching These two concepts are often confused. Response Caching Response caching mainly relies on HTTP caching semantics and headers. Output Caching Output caching is controlled by ASP.NET Core and allows your application to decide which responses should be cached and for how long. Output caching provides more control over server-side response caching. 1. Add Output Caching Start by registering the output-cache services. var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddOutputCache(); var app = builder.Build(); app.UseOutputCache(); app.MapControllers(); app.Run(); The important pieces are: AddOutputCache() ↓ Configure cac
AI 资讯
NuGet Restore Failing with 'Unable to find version' Package? Check Your NuGetToolInstaller Version!
The Problem In one of our Azure DevOps pipelines, nuget restore suddenly started failing with an error stating, in essence, that the requested package could not be found in the referenced version. The task referencing the package hadn't changed — yet the restore stage kept failing. At first glance, this looks like an issue with the package source, some caching effect, or a broken .nuspec/lockfile. It wasn't. The Root Cause The actual culprit was the version of the NuGetToolInstaller@1 task itself. The pipeline had NuGet pinned to version 6.12.2. The Fix Bump the versionSpec in the NuGetToolInstaller@1 task from 6.12.2 to 7.9.0: - task : NuGetToolInstaller@1 displayName : ' Use NuGet 7.9.0' inputs : versionSpec : 7.9.0 checkLatest : false That's it. After the update, nuget restore ran through cleanly again.
AI 资讯
MFA Enabled Is Not MFA Verified
A two-factor flag in the user store looks like a reassuring authorization check. It tells us the account has a second factor configured. For a sensitive operation, however, that is only half the question. The other half is about the session in front of us: did this cookie actually complete a second-factor challenge? Those facts can change independently. Treating them as interchangeable can silently promote an old password-only session after the account enables MFA. Two questions that look like one Account capability answers questions such as: Is a factor enrolled now? Could the account complete an MFA challenge? Has that capability since been disabled? Session assurance answers different questions: Which authentication steps produced this session? Did the framework issue this cookie after an MFA challenge? Is the evidence trusted, or merely a user-supplied claim? An enrolled account can still have a password-only session. A previously verified session can also outlive a later change to the account’s factor state. One signal cannot safely stand in for both. The transition that exposes the gap Snapshot tests often miss this because the final state looks correct. The account has MFA enabled, the user is authenticated, and a policy succeeds. Now test the transition instead: Sign in with a password and receive a normal application cookie. Enable MFA for the account without replacing that cookie. Use the original cookie against a sensitive operation. If authorization checks only the current enrolment flag, step three may succeed. Nothing about the original authentication ceremony changed, but the session has effectively been upgraded by a later database write. That is the important boundary: changing account capability must not rewrite the history of an already-issued session. Use two independent signals A generalized policy can be expressed like this: if (! session . IsAuthenticated || ! session . HasTrustedMfaEvidence ) return Deny ; if (! await accountStore . IsMfaStil
AI 资讯
14 Years of Enterprise ASP.NET, Part 4: Azure, Observability & AI in Real Systems
Originally published at prepstack.co.in Part 4 of 4 — 14 Years of Enterprise ASP.NET (finale). Where the system actually runs: choosing Azure architecture by cost and scaling profile, making the system observable, and treating AI as a real architectural component — not a demo. Running example: Mattrx — .NET 9 / ASP.NET Core, 110k MAU, Azure SQL, ~3,200 req/sec peak. Lesson 10 — Azure: match the platform to the workload Pick the compute by your scaling and operational profile, then right-size — don't default to the biggest box or the trendiest platform. Most enterprise .NET runs perfectly on Azure App Service; you reach for Container Apps or AKS when you have a specific reason, not because Kubernetes is on your résumé. The decision framework: App Service for standard web/API (default), Container Apps when you want containers + scale-to-zero without running a cluster, AKS only when you genuinely need its control plane and have the ops capacity. A 5-person team has no business running Kubernetes. Over-provisioning is the most common and most invisible cloud waste — it never pages anyone, so nobody fixes it. Right-sizing the web tier (P2v3×6 always-on → P1v3×2 + autoscale), moving to managed Redis, and tuning the SQL tier saved roughly $2,000/month total — with better peak headroom, because autoscale handles the month-end burst the fixed fleet was over-sized for. Lesson 11 — Observability is essential For years I "had logging" and was still blind in production. The shift from logging to observability — answering new questions about a running system without shipping new code — is the difference between a 4-minute incident and a 4-hour one. You can't fix what you can't see, and you can't see what you didn't instrument. Three pillars, tied by a correlation ID: logs (what happened), metrics (how much/how often), traces (where the time went). // structured fields + a correlation scope so every line in the request is linkable using ( logger . BeginScope ( new Dictionary < str
AI 资讯
Voice In. Words Out: The Free, 100% Offline Voice Typing App for Windows
Imagine this: You’re drafting a long email, writing a report, or responding to a wave of Slack messages. Instead of hunching over your keyboard and typing at 40 words per minute, you simply hold down Ctrl + Space , speak your thoughts at 150+ words per minute, and release the keys. Instantly, clean, perfectly punctuated, polished text appears right where your cursor is. Meet Vacanam — a free, 100% private, offline voice typing tool built for Windows 10 & 11. 😫 Why Most Voice Typing Tools Are Frustrating If you’ve ever tried built-in dictation tools or commercial transcription services, you’ve likely run into the same annoyances: They Send Your Voice to the Cloud : Many tools stream your microphone audio to remote servers. If you work with sensitive emails, client data, or private thoughts, that’s an immediate dealbreaker. They Require an Internet Connection : Try dictating on an airplane, during spotty Wi-Fi, or in a secure offline room — they simply refuse to work. Punctuation is a Headache : You have to awkwardly say things like "Hello comma how are you question mark" just to get a basic sentence right. Subscription Fatigue : Most good dictation apps charge $10 to $30 every single month. We built Vacanam (वचनम् — Sanskrit for Voice & Speech ) to fix all of this once and for all. 🌟 The Superpowers: What Makes Vacanam Different? 1. 🎙️ Works in Every Single Windows App Vacanam doesn’t trap you inside a special recording window. It works universally: Productivity & Docs : Microsoft Word, Google Docs, Notion, Obsidian, OneNote Communication : Slack, Microsoft Teams, WhatsApp Desktop, Discord, Outlook, Gmail Browsers & Editors : Chrome, Edge, Firefox, Notepad, VS Code, Terminals Just click into any text box, hold Ctrl + Space, speak, and let go. 2. 🪄 Automatic AI Polish (No More "Ums" or Missing Commas) When we talk, we hesitate, say "um" , repeat words, and forget punctuation. Vacanam features an optional Built-in AI Assistant that runs silently on your computer: Remov