开发者

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

开发者 https://www.devze.com 2023-01-10 13:53 出处:网络
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.

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 pro开发者_开发知识库blem 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


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/"));
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消