【问题标题】:how to route to css/js files in mvc.net如何路由到 mvc.net 中的 css/js 文件
【发布时间】:2011-08-07 06:40:25
【问题描述】:

我正在尝试使用 mvc.net 中的路由向我的应用程序添加一个区域。 对于我添加的控制器:

routes.MapRoute(
                "Area1", // Route name
                "Area1/{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

我怎样才能以相同的方式路由 css/js 文件,即我想让 area1/content/site.css 转到 /content/site.css/content/area1/site.css

谢谢

【问题讨论】:

    标签: css asp.net-mvc routing


    【解决方案1】:

    喜欢这个

    /content/site.css

    如果你想总是转到 site.css:

    routes.MapRoute(
                    "Area1", // Route name
                    "/{action}/site.css", // URL with parameters
                    new { controller = "Area1", action = "content" } // Parameter defaults
                );
    

    如果您想通过提供 css 名称转到不同的 css:

    routes.MapRoute(
                    "Area1", // Route name
                    "/{action}/{resource}.css", // URL with parameters
                    new { controller = "Area1", action = "content", resource = UrlParameter.Optional } // Parameter defaults
                );
    

    /content/area1/site.css

    routes.MapRoute(
                        "Area1", // Route name
                        "/{action}/Area1/{resource}.css", // URL with parameters
                        new { controller = "Area1", action = "content", resource = UrlParameter.Optional } // Parameter defaults
                    );
    

    【讨论】:

    • 感谢您的回答。这对我不起作用,因为我没有尝试路由到控件/动作,我正在尝试路由到静态 css 文件。
    【解决方案2】:

    我没有找到使用 mvc 路由执行此操作的方法,我最终做的是: 我在 http 模块中运行了这段代码:

    void context_BeginRequest(object sender, EventArgs e)
            {
                HttpApplication Application = sender as HttpApplication;
    
                var match = r.Match(Application.Request.Url.AbsolutePath);
                if (match.Success)
                {
                    var fileName = match.Groups[2].Value;
                    Application.Context.RewritePath("/" + fileName);
                }
            }
    

    r 在我的例子中是一个正则表达式:

    private readonly Regex r = new `Regex("^/gmail(/canvas)?/((content|scripts|images|tinymce).*)$", RegexOptions.IgnoreCase);`
    

    在 global.asax 中我添加了:

    routes.IgnoreRoute("{*staticfile}", new { staticfile = @".*\.(css|js|gif|jpg)(/.*)?" });
    

    防止 mvc.net 路由这些请求。

    可能还需要设置 iis6/iis7 以通过 mvc.net 将请求路由到静态文件,但我忘记了细节。

    我从几个我不记得的帖子中选择了这个方法,所以我很抱歉我不能给予适当的信任。

    【讨论】:

      猜你喜欢
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多