Can't use relative paths with areas in ASP.NET MVC 2

微笑、不失礼 提交于 2019-12-13 02:38:35

问题


In my application I have an area call Mobile. In this area I have a folder call Assets where we place all our css, javascript and images.

Accessing the views works just fine. http://localhost/webapp/mobile/stuff

The problem is when I access my css, javascript and images.

I cannot do something like this in my view.

<img src="Assets/css/styles.css" />

The reason is because the real url is: http://localhost/webapp/areas/mobile/assets/css/styles.css

Is there a way to map http://localhost/webapp/areas/mobile to http://localhost/webapp/mobile for static files?

Thanks, Randall


回答1:


The solution I came up with was to use a simple IHTTPModule, that would rewrite the urls for me. Here is the method I implemented for the BeginRequest event.

void BeginRequest(object sender, EventArgs e)
{
    var context = HttpContext.Current;
    var path = context.Request.Path;

    // Add Areas to the Mobile path, so we don't have to specify it manually.
    // This is mainly for handling static resources that you place in areas.
    if (!path.Contains("Mobile/")) return;
    if (path.EndsWith(".png") ||
        path.EndsWith(".gif") ||
        path.EndsWith(".css") ||
        path.EndsWith(".js") ||
        path.EndsWith(".htm") ||
        path.EndsWith(".cache"))
        context.RewritePath(path.Replace("Mobile/", "Areas/Mobile/"));
}



回答2:


You probably need to do something like this:

<img src="../../Mobile/Assets/css/styles.css" />

...depending on where your current directory actually is. You can also try something like:

<img src="~Mobile/Assets/css/styles.css" />

A good way to find out what the actual path should be is to drag the asset (in this case styles.css) from the Project Explorer to your view, and let Visual Studio create the path for you.



来源:https://stackoverflow.com/questions/3397924/cant-use-relative-paths-with-areas-in-asp-net-mvc-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!