简体   繁体   中英

asp.net routing when using MVC & Web-API

I have a project with both ASP.NET MVC and Web API in one.

And I have to redirect requests from /assets/x/y/z.ext to /content/assets/x/y/z.ext

This is the code I wrote:

public class AssetsController : Controller
{
    // GET: Assets
    public ActionResult Redirect()
    {
        var url = HttpContext.Request.FilePath;
        return base.Redirect("~/Content" + url);
    }
}

And this is the content of App_Start/RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute("Assets", "assets/{*url}", new { controller = "Assets", action = "Redirect" });

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Now for some reason this is not working. Any help to get this fixed is welcome.

FYI:

  • The code was copied from another project where it did work.
  • The other project was pure MVC
  • I have placed a breakpoint in the Assets controller and it is never called.

I have found the solution:

Apparently routing does not apply to 'known' file types. So the resource I was requesting was " http://localhost:8080/assets/images/logo.png " and this did not trigger the assets controller. But " http://localhost:8080/assets/images/logo.png/ " did.

So I had to specify that I wanted all files in the assets folder routed. This is done by adding an extra configuration in the web.config file:

  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />

      <add name="AssetsPathContainsFiles" path="/assets/*" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

Remark: It was important to use path="/assets/*" and not path="assets/*" becuase the second one would also try to handle paths like "/content/assets/images/logo.png" while this should be handled by the standard static file handler ... (I assume that the leading slash causes the path to be rooted)

(When I used path="assets/*" it caused a loop and the browsers gave me "to many redirect" errors.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM