To prevent invalid path requests in an MVC application, validate and canonicalize the incoming path before it reaches routing or file access, reject anything that escapes the expected root, and return a clean 400 or 404 instead of letting the framework resolve it. The key condition is that validation has to happen on the server against a normalization-aware rule, not by string-matching slashes. That single principle prevents most traversal problems in ASP.NET Core MVC, Spring MVC, and similar frameworks, though the exact hooks differ. What follows is a framework-neutral method with concrete implementation notes for both stacks, plus the failure cases that trip up teams who think they've already handled it.
The phrase "invalid path request" covers two related but distinct threats. One is a malformed or traversal-style URL (../, encoded dots, null bytes, overlong sequences) aimed at reading files outside the intended directory. The other is a route value that is syntactically legal but semantically wrong—an ID that doesn't exist, a slug with forbidden characters, a path segment that exceeds length limits. MVC frameworks handle these differently. Route matching decides whether a request reaches your controller at all; model binding and your own validation decide whether the value is acceptable once it does. Preventing invalid path requests means covering both layers, because a request that never matches a route still has to be handled gracefully, and a request that matches a route but carries a hostile parameter still has to be rejected.
Where path requests actually get dangerous in MVC
MVC routing is a two-stage decision. The router extracts segments from the request URL, matches them against a route template, and produces route values. Those route values then get bound to action parameters. If your action takes a string path, string fileName, or string id and uses it to build a filesystem path, a database key, or a redirect target, you've created the injection point.
The classic attack is path traversal: a request like /files/../../etc/passwd or its encoded variants (%2e%2e%2f) tries to climb out of the intended directory. Whether it succeeds depends on whether the server normalizes the path before or after your check, and on how the web server in front of MVC (IIS, Kestrel, Tomcat, nginx) handles encoded slashes and dots. Different servers normalize at different points, which is exactly why in-app string checks fail.
A subtler problem is that route templates with a catch-all parameter (like ASP.NET Core's {path} or a Spring / pattern) will happily capture encoded traversal sequences. A catch-all is convenient for file-serving endpoints and nearly always wrong for anything that touches the filesystem without a second layer of validation.
There's also the semantic case: route values that pass routing but should never reach business logic—a user-supplied returnUrl used for redirects (open redirect), a file parameter used directly in File.ReadAllBytes, a culture segment interpolated into a resource path. These aren't traversal attacks in the strict sense, but they produce invalid or unsafe path requests and need the same treatment.
The prerequisite: decide what a valid path is before you write a check
You can't validate against a rule you haven't defined. Before touching code, write down the exact shape of every path-like input your application accepts. For a file download endpoint, that might be "a base name from a fixed allowlist of extensions, no directory separators, maximum 255 characters, URL-decoded exactly once." For a content route, it might be "a slug matching ^[a-z0-9-]{1,80}$." For a nested resource, it's usually "a numeric or GUID identifier, nothing else."
That definition should specify four things:
Allowed character set. Prefer allowlists over blocklists. Unicode normalization and case-folding can turn a "forbidden" character into a legal one on some filesystems. Canonical form. Define whether the value is decoded, trimmed, lowercased, and whether trailing dots or spaces are rejected (Windows strips trailing dots and spaces from filenames, so file.txt. and file.txt can collide). Maximum length. Path segments, total path length, and query string length all have framework and OS limits; pick values below them. Resolution base. For filesystem access, the only legitimate base is a fixed, absolute directory chosen by configuration—never something derived from the request.
Once that's written down, the validation code becomes a straightforward implementation of the rule rather than a guess about which malicious strings to block.
Step-by-step: blocking invalid path requests
The order below matters. Decode first, normalize second, validate third, resolve fourth, and check containment fifth. Reversing any of these creates bypasses.
-
Capture the raw value and decode it exactly once. Most frameworks already URL-decode route values, but if you read the raw query string or header, decode it yourself—once. Double-decoding is a common bug: %252e%252e decodes to %2e%2e and then to ... Decode once, then validate the decoded form.
-
Reject control characters and null bytes outright. A null byte (%00) historically truncated paths in native APIs. Even where it's harmless, it's never legitimate in a path segment. Strip or reject anything in the C0 control range.
-
Normalize using the platform's own path API, not string replacement. In .NET, Path.GetFullPath resolves . and .. segments relative to a base. In Java, java.nio.file.Path.normalize() does the equivalent. Let the runtime do the canonicalization; hand-rolled .. stripping gets edge cases wrong (backslashes on Windows, mixed separators, UNC prefixes).
-
Resolve the candidate path against a fixed base directory. Combine the validated relative segment with Path.Combine(baseDir, segment) (.NET) or baseDir.resolve(segment) (Java). The base directory comes from configuration and is verified to exist at startup.
-
Check that the resolved path is still inside the base. Compare the resolved full path to the base with a trailing separator appended, using an ordinal, case-appropriate comparison. If the resolved path doesn't start with the base plus separator, reject it. This single containment check is what actually stops traversal—everything before it is defense in depth.
-
Enforce the allowlist and length limits from your definition. Character set, extension, segment count, total length. This catches semantic mistakes the containment check can't, like file=../../other-app/secrets.txt where "other-app" happens to sit under a shared parent.
-
Return a clean status. Malformed or traversal-style requests get 400 Bad Request. Well-formed paths that don't exist or aren't allowed get 404 Not Found. Don't leak the resolved path, the base directory, or the specific rule that failed; log those server-side with a correlation ID.
-
Log and monitor rejections. A spike in 400s from traversal attempts is a signal. Correlate by client, increment a counter, and alert on threshold. This is how you find out whether your rule is too strict (false positives) or under attack.
Success check: send /files/..%2f..%2fweb.config (encoded traversal) and /files/%2e%2e/%2e%2e/etc/passwd (dot-segment encoding) and confirm both return 400, not a file. Then send a legitimate nested file and confirm it downloads. If the traversal requests return 404 because routing rejected them before your code ran, that's also acceptable—but verify explicitly, because a route that doesn't match may still be logged as an error by the framework.
Doing it in ASP.NET Core MVC
ASP.NET Core gives you three natural interception points, and you should use at least two of them.
A custom route constraint (IRouteConstraint) attached to the route template rejects values that fail a regex or length check before the action is selected. For example, {fileName:regex(^[a-zA-Z0-9._-]{{1,255}}$)} constrains the segment to a safe character class. Constraints run during route matching, so a non-conforming request returns 404 without entering your controller.
A resource filter or action filter validates bound parameters after model binding and before the action body runs. This is the right place for the containment logic, because you have access to the resolved path and configuration. A filter that returns BadRequest() short-circuits cleanly.
For filesystem access specifically, avoid building paths in the controller at all. Put them behind a service that takes only a validated identifier, resolves against a configured base, performs the containment check, and returns a Stream or a typed result. The controller then can't accidentally bypass the rule.
Also watch the catch-all route. If you use {**path}, you've told the router "capture anything," so all validation shifts to your filter. That's fine if the filter is airtight, but it's an easy place to forget the containment check. Prefer explicit segment templates where possible.
Finally, configure request limits—MaxRequestBodySize, query string length, and path length in Kestrel or IIS—so absurd inputs are rejected at the server edge before routing allocates anything.
Doing it in Spring MVC
Spring's model is similar but the hooks have different names. A route pattern like /files/{fileName:[a-zA-Z0-9._-]{1,255}} uses a regex path variable to constrain the segment. Spring's PathPattern parser (the default in Spring MVC since 6.0) handles this efficiently and rejects non-matching requests at the mapping stage.
For decoding and normalization, read the path variable as a String, then use Paths.get(base, value).normalize() and startsWith(base) for containment. Spring decodes the URI once during request parsing; if you need the raw value, use HttpServletRequest#getRequestURI() but remember it's undecoded and includes the context path—handle that carefully or you'll introduce your own bypass.
A HandlerInterceptor or a @ControllerAdvice exception handler can centralize the 400/404 responses and logging so individual controllers stay clean. Spring Security's StrictHttpFirewall (enabled by default in recent versions) already blocks many encoded-slash and traversal patterns at the filter level, but it's a first line, not a substitute for the containment check.
The same architectural advice applies: don't let controllers build filesystem paths from request values. A service that accepts a validated key and returns a resource keeps the invariant in one place.
What the framework will and won't do for you
MVC frameworks are good at route matching and bad at semantic path safety. They will not, by default:
Prevent a catch-all route from capturing traversal sequences. Guarantee that a route value used in a filesystem path is confined to a base directory. Stop an open redirect via a returnUrl parameter. Distinguish "malformed path" (400) from "not found" (404) in a way that matches your API contract.
They will, in most default configurations, reject requests with encoded slashes in some servers and accept them in others. That inconsistency is the reason to do the containment check in application code rather than trusting the reverse proxy. A request that reaches your action with ../ in a parameter is a request your code must handle, because you can't rely on the front end having blocked it.
The honest limit: path validation is context-dependent. "Invalid" for a file download endpoint (no separators, extension allowlisted) is different from "invalid" for a wiki page (slugs with hyphens and Unicode allowed). There is no universal regex. The method—define the rule, decode once, normalize with the platform API, resolve against a fixed base, check containment, enforce the allowlist, return a clean status—is what generalizes. The specific rule is yours to write and test.
Edge cases that bypass naive checks
A few failure modes deserve explicit tests because they defeat string-based validation:
Encoded separators. %2f and %5c may or may not be decoded before your check depending on the server. Test both forward slash and backslash encodings.
Double encoding. %252e%252e%252f decodes to %2e%2e%2f and then to ../ if decoded twice. Decode exactly once and validate the result.
Unicode and overlong forms. Some filesystems normalize Unicode differently than your string comparison. If you allow non-ASCII, compare normalized forms and be aware that two different byte sequences can map to one filename.
Trailing dots and spaces on Windows. file.txt. resolves to file.txt. If your allowlist checks the extension, file.txt. passes and then resolves to a file you didn't intend to serve. Reject trailing dots and spaces.
Alternate data streams on NTFS. file.txt::$DATA can expose file content through an unexpected path. Reject : in segments on Windows.
Symlinks. A symlink inside the base directory can point outside it. The containment check on the resolved string path will pass, but open() follows the link. If symlinks are a concern, resolve the real path (Path.GetFullPath after FileInfo.LinkTarget checks, or toRealPath() in Java) and re-run containment. This is the case where "check the string" genuinely isn't enough.
Case sensitivity. Linux is case-sensitive, Windows is not, macOS is case-insensitive by default. If your containment comparison uses ordinal case-sensitive matching on a case-insensitive filesystem, Base/../base/secret might slip through. Use the platform's comparison semantics or, better, resolve and compare real paths.
Each of these is a test case, not a paragraph of theory. Add them to an integration suite that hits the actual HTTP endpoint, because unit-testing the validation function won't catch a server that decodes before your code sees the value.
Operational habits that keep the defense working
Validation code drifts. Someone adds a new endpoint that takes a path parameter and forgets the service wrapper. Someone weakens a regex to accept a new file type. The defenses that hold are the ones enforced by structure, not discipline.
Put all path-accepting endpoints behind a single service or base class that applies the rule. Make the raw request value unavailable to controllers—bind to a validated value object instead of a string. Add an integration test per endpoint that sends a traversal payload and asserts 400 or 404. Run a linter rule or a code review checklist item for any action parameter named path, file, fileName, url, or returnUrl.
Log rejected paths with the rule that failed and the requested URL, but not the resolved filesystem path. Set an alert on the rejection rate; a sudden jump is either an attack or a client that's sending malformed URLs, and both are worth knowing about.
For redirect parameters, the same principle applies with a different base: resolve the returnUrl against your application's allowed host list, not against the request's Host header, and reject anything that isn't a relative path or an absolute URL on an allowlisted domain. Open redirect is the same class of bug as path traversal—a user-controlled path that the framework will happily honor.
What to expect when you implement this: traversal payloads return 400, nonexistent legitimate paths return 404, and legitimate nested paths resolve. If a traversal payload returns 200 with file content, the containment check is missing or ordered wrong—most often the code checked the raw string before normalization, or normalized after combining without re-checking. Start by logging the value your action actually received; that tells you whether the failure is at the server, the router, or your validation. If you're serving files from a network share or a user-writable directory, and you can't get containment plus real-path resolution to hold under test, that's the point to involve a security engineer rather than tune the regex further.
FAQ
Does a WAF or reverse proxy make app-level checks unnecessary? No. A WAF blocks known patterns at the edge, but encoded variants, internal callers, and configuration changes can bypass it. The containment check in application code is the invariant that survives an edge change.
Is validating the route template enough? Only for semantic constraints. Route regexes run before model binding and can't see the resolved filesystem path, so they can't enforce containment. Use both: a route constraint for shape, a service or filter for containment.
What status code should traversal attempts get? 400 for malformed or clearly hostile input, 404 when the path is syntactically valid but doesn't resolve to an allowed resource. Be consistent across endpoints and document it, because clients and monitoring depend on the distinction.