Search code examples
c#asp.net-mvcuriserver.mappath

Server.MapPath with query string in ASP.NET MVC


After some 15 mins of Goooooogling, I cannot find a solution to this simple problem. So some little help?

The application is hosted in a web subfolder of the website, I need to map a relative Uri (which is a Hello action in the RouteController which takes an int and a string as parameters):

"~/Route/Hello/129?name=kennyzx"

to

http://myserver/web/myapplication/Route/Hello/129?name=kennyzx

If I use

HttpContext.Current.Server.MapPath("~/Route/Hello/129?name=kennyzx");

It throws an exception because the question mark ? is an illegal character.

So I need to first separate the Uri into two parts ~/Route/Hello/129 and ?name=kennyzx, then MapPath takes the first part, and Path.Combine concatenate the result of MapPath and the query string.

Is there a simpler way to do this?

I realize I am using the wrong API, it actually expands to the real file path on my server!

This is what I am trying to do:

I have a bunch of relative uris and I want to write a function to expand them to absolute uris, in Razor page.

@{
    ViewBag.Title = "Route Testing";
    var link1 = "/Route/Hello/129?name=kennyzx";
    var link2 = "~/Route/Hello/129?name=kennyzx";
}

@functions{
    private static string GetAbsoluteUri(string link)
    { 
        string absoluteUri = HttpContext.Current.Server.MapPath(link);
        return absoluteUri;
    }
}

<h2>Route Testing</h2>

<a href="@link1">@link1</a><br />
<a href="@link2">@link2</a><br />
<a href="@GetAbsoluteUri(@link2)">@link2</a><br />

But none of the above get the correct absolute path.

The first expands to http://myserver/Route/Hello/129?name=kennyzx,

The second expands to http://myserver/web/myapplication/~/Route/Hello/129?name=kennyzx

The third throws an exception and that is why I am asking this question.


Solution

  • Server.MapPath returns the actual path on the server like file:///C:/somefolder/somefile. It is not used to resolve relative urls.

    Turns out what I am looking for is @Url.Content to resolve relative urls in Razor page.

    @{
        ViewBag.Title = "Route Testing";
        var link1 = "~/Route/Hello/129?name=kennyzx";
    }
    
    <h2>Route Testing</h2>
    
    <a href="@Url.Content(@link1)">@link1</a><br />