配置RouteMap后访问静态文件URL无法触发重定向的问题求助
The core issue here is that static files (like your logo.png) are served directly by the web server (IIS/Kestrel) before MVC routes are even processed. When you hit http://localhost:55306/Content/Admin/img/logo.png, the server finds the physical file in your web root and serves it immediately—your Content action method never gets called.
Here are three straightforward solutions to fix this:
Solution 1: Force Existing Files to Use MVC Routing
Tell ASP.NET to route requests for existing files through the MVC pipeline instead of serving them directly.
- Open your
RouteConfig.csfile. - Add this line before defining your custom route:
routes.RouteExistingFiles = true; - To avoid breaking other static files (like CSS/JS), add
IgnoreRouteentries for file types you still want to serve normally:routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{*css}", new { css = @".*\.css(/.*)?" }); routes.IgnoreRoute("{*js}", new { js = @".*\.js(/.*)?" }); - Keep your existing route definition as-is. Now, requests for
logo.pngwill hit yourAdminController.Contentmethod and trigger the redirect.
Solution 2: Use URL Rewrite (Simpler for Single Files)
If you only need to redirect this specific image and don't want to modify global routing behavior, add a rewrite rule directly in your web.config:
<system.webServer> <rewrite> <rules> <rule name="Redirect Logo to Signin" stopProcessing="true"> <match url="^Content/Admin/img/logo.png$" /> <action type="Redirect" url="/Signin" redirectType="Temporary" /> </rule> </rules> </rewrite> </system.webServer>
This rule will intercept the request before it reaches MVC and redirect it immediately.
Solution 3: Move the Static File Out of the Web Root
If you don't want the server to have direct access to logo.png, move it to a directory outside your web root (e.g., a folder named PrivateAssets at the project root). Since the server can't find the file physically, the request will fall through to your MVC route, triggering the redirect.
Note: You'll need to update any other references to this image if you take this approach.
Quick Sanity Check
Double-check that your Content method is indeed inside the AdminController class—this is an easy mistake to make!
public class AdminController : Controller { public void Content() { Response.Redirect("/Signin"); } }
内容的提问来源于stack exchange,提问作者Joseph D.

