Any way to get a file system path for a razor page? - filepath

For a page 'TestModel' in 'Pages/TestPages/' get a string like:
/linux or project root/project-name/Pages/TestPages/
Edit: I'm not looking to get a path from inside a running page. Let's say from startup.cs
Edit 2: I'm looking something like this:
string GetPath(PageModel Page)
string path = GetPath(TestModel)
path: "/linux or project root/project-name/Pages/TestPages/"

Related

How to save the correct location of file in table? getting error is not a valid virtual path

I was trying to upload some images in my website using input type=file in my asp.net mvc project.while storing the image I used the following code and it is saving the image successfully.
var path2 = Path.Combine(Server.MapPath("~/Images"), filename.jpg);
artwork.SaveAs(path2);
After that I need to save the whole link ( http://example.com/Images/filename.jpg) into my table column.
for that i tried this
tablename.imagelink = path2 ;
then in table column I am getting like
D:\xxxxx\yyyy\example\Images\filename.jpg
then i tried to save the whole link directly
tablename.imagelink = Path.Combine(Server.MapPath("http://example.com/Images/"), filename.jpg);
at that time I am getting an error: "is not a valid virtual path error"
How to solve this. ?
Server.MapPath requires the virtual path of the web server, and you get the error because you're passing the full path like this:
Server.MapPath("http://example.com/Images/")
You need to keep using this:
Server.MapPath("~/Images")

How to Route to Url *with* Extension

I'm trying to deliver my blog's sitemap.xml file generated by a Razor view, like so in my _AppStart.cshtml file:
//sitemap
RouteTable.Routes.MapWebPageRoute("sitemap.xml", "~/pages/shared/sitemap.cshtml");
This route is ignored for some reason, and I get a 404. It works fine if I route it to "/sitemap", but the moment I include the file extension it breaks. I'm assuming IIS is doing something with the request before ASP.NET gets hold of it, but I"m not sure what to do about it.
Try making the extension a parameter:
RouteTable.Routes.MapWebPageRoute(
"sitemap.{extension}", // route pattern
"~/pages/shared/sitemap.cshtml", // physical file
defaultValues: new {extension = "xml"}, // defaults
constraints: new {extension = "xml"}); // constraints (regex)

Rewrite urls from user submitted HTML

I use one WYSIWYG editor in a small cms. It allows users to upload files, images, etc. If I add image named dog.jpg, in source I'll get:
<img src="/myweb/userfiles/images/dog.jpg" />
I can save this to a database and use it later on any page, until I move my site to a live domain.
myweb is virtual directory in IIS. "/" points to root, in this case localhost, so I have to use "/myweb". However when I upload site to server and copy database there, all links will be broken, because there is no "myweb" folder on server.
My idea was to replace "/myweb" on save with empty string. I also have to replace full url, which editor creates for some files. On display I would have to add correct Application dir. I would probably save both versions in database, and only on server change force display version to update.
By now I've come up with:
p = p.Replace("href=\"" + fullUrl, "href=\"").Replace("src=\"" + fullUrl, "src=\"").Replace("href=\"" + partialUrl, "href=\"").Replace("src=\"" + partialUrl, "src=\"");
Which is ugly, hard to maintain and inefficient. I guess better approach would be to use regex, but I don't know how to do it.
My question is, can anyone recommend good article, blog/forum post on this? If you have other solution, great.
I am unsure the regex version has any of the characteristics you mention in this case.
That said, you can do:
string ReplaceUrlPaths(string html, string partialPath, string fullPath)
{
var pattern = string.Format("((href|src)=\")({0}|{1})", partialPath, fullPath);
var regex = new Regex(pattern);
return regex.Replace(html, m => m.Groups[1].Value);
}
[TestMethod]
public void TestMethod10()
{
var input = #"<img src=""/myweb/userfiles/images/dog.jpg"" />";
//carefull with any special regex char in the paths
var replaced = ReplaceUrlPaths(input, "/myweb", "/some/full/path");
Assert.AreEqual(
#"<img src=""/userfiles/images/dog.jpg"" />",
replaced);
}
If you are proceeding with that, refactor it to instantiate the regex once with the compile option(as the partialPath and fullPath won't be changing).
Also consider avoiding it all, by defining a web site with an alternate port to just have it as a root Url.
Store the local root path separately from the images. For each image, store the relative path to that image.
When displaying images locally, use the local root merged with the relative path. When you publish to the remote server, you add the remote root to the relative path.
Does your WYSIWYG editor allow you to configure the base URL e.g. so that paths to images can use relative paths? I think the FCKEditor has something like FCKConfig.BaseHref in it's config file that does something like this.
Alternatively can you run the site as a root site using the ASP.NET 2.0 web server? Then you wouldn't have to worry about rewriting paths to images as you could just use paths from the webroot.

Get virtual path for a full path in asp classic

How can I get the virtual path for a full path in ASP classic. Note that the full path may be under a virtual directory and therefore the simplistic
virtPath = Replace(fullPath, Server.MapPath("/"), "")
method will not work.
Edit: To clarify, an example follows
Full Windows File Path (known):
\\MyServer\MyShare\Web\Site\Logs\Test.txt
My Website has a Virtual directory
called Logs that Points to \\MyServer\MyShare\Web\Site\Logs\.
Virtual Path (unknown): /Logs/Text.txt
Http path (unknown, needed):
http://Site/Logs/Test.txt
The code is in a asp page in the main app, not under any virtual directories. It is located on a separate server from the file in question.
IIS 6.0
How do I find the virtual path from the full file path?
In case anyone's interested, Anthony Jones' answer showed me the way to getting the application's relative root consistently. So if you have a site at http://example.com and a local development equivalent at http://localhost/example, you can find your root with this function:
Function ToRootedVirtual(relativePath)
Dim applicationMetaPath : applicationMetaPath = Request.ServerVariables("APPL_MD_PATH")
Dim instanceMetaPath : instanceMetaPath = Request.ServerVariables("INSTANCE_META_PATH")
Dim rootPath : rootPath = Mid(applicationMetaPath, Len(instanceMetaPath) + Len("/ROOT/"))
ToRootedVirtual = rootPath + relativePath
End Function
You can then call it like this to get the root path:
ToRootedVirtual("/")
Which will return:
/ on example.com
/example/ on localhost/example
You can also use it without the slash:
ToRootedVirtual("")
If I've understood the question.
Assumption
The full path is a path with in the current application or a child application. It is not a path limited to the parent nor a path into a sibling application. The desired path is relative to the current applications path.
Scenario 1
A path such as
"/someApp/someFolder/someSubFolder/file.ext"
should resolve it to:-
"~/someFolder/someSubFolder/file.ext"
(although the ~/ notation isn't something ASP classic understands).
Scenario 2
"/someApp/someSubApp/SomeSubFolder/file.ext"
you still want:-
"~/someFolder/someSubFolder/file.ext"
Scenario 3
The app is the root application of the site:-
"/someFolder/someSubFolder/file.ext"
would still become
"~/someFolder/someSubFolder.file.ext"
Solution
The key to solving this is:-
Dim sAppMetaPath : sAppMetaPath = Request.ServerVariables("APPL_MD_PATH")
For the above set of scenarios this will result in something like:-
"/LM/W3SVC/33230916/Root/someApp"
"/LM/W3SVC/33230916/Root/someApp/someSubApp"
"/LM/W3SVC/33230916/Root"
Also
Dim sInstanceMetaPath: sInstanceMetaPath = Request.ServerVariables("INSTANCE_META_PATH")
will in all the scenarios return
"/LM/W3SVC/33230916"
With some mathematical reduction we can arrive at the function:-
Function ToAppRelative(virtualPath)
Dim sAppMetaPath : sAppMetaPath = Request.ServerVariables("APPL_MD_PATH")
Dim sInstanceMetaPath: sInstanceMetaPath = Request.ServerVariables("INSTANCE_META_PATH")
ToAppRelative = "~/" & Mid(virtualPath, Len(sAppMetaPath) - Len(sInstanceMetaPath) - 3)
End Function
Although there may be a better way, I always did this by creating a config variable where I manually specify the root path that is not part of the virtual path. This is because you do not know if the site will be deployed as root, under a folder in root web, or in a virtual directory.
well, my answer isn't better than OrbMan's...
I have organized my app in such a way that every include is relative...
that is
instead of \myapp\lib\somefile.asp I use ..\lib\somefile.asp
in other cases I just do what Orbman said...
Here's how you solve root-relatie pathing in html via ASP so your site can be portable to different hosting directories.
This little snippet will produce the correct prefix to set your URLs:
Mid(Request.ServerVariables("APPL_MD_PATH"),Len(Request.ServerVariables("INSTANCE_META_PATH"))+6)
You can use this in LINKs, IMGs, hyperlinks, etc as follows:
<link href="<%= Mid(Request.ServerVariables("APPL_MD_PATH"),Len(Request.ServerVariables("INSTANCE_META_PATH"))+6) %>/assets/css/master.css" rel="stylesheet" type="text/css" />
so, code your paths to be root-relative (starts with a /) and then put this snippet right in front of that first slash, inside the quotes:
The server's virtual path is:
<%Response.Write "http://" & Request.ServerVariables("server_name") &
left(Request.ServerVariables("SCRIPT_NAME"),InStrRev(Request.ServerVariables("SCRIPT_NAME"),"/")) %>
</p>

how can an .ASPX page get its file system path?

I have a page something.aspx, with associated codebehind something.aspx.cs. In that codebehind, I want to know the filesystem location of something.aspx. Is there any convenient way to get it?
Update: I got several excellent answers, which unfortunately didn't work because of something else crazy I'm doing. I'm encoding some additional information on the URL I pass in, so it looks like this:
http://server/path/something.aspx/info1/info2/info3.xml
The server deals with this OK (and I'm not using querystring parameters to work around some other code that I didn't write). But when I call Server.MapPath(Request.Url.ToString()) I get an error that the full URL with the 'info' segments isn't a valid virtual path.
// File path
string absoluteSystemPath = Server.MapPath("~/relative/path.aspx");
// Directory path
string dir = System.IO.Path.GetDirectoryName(absoluteSystemPath);
// Or simply
string dir2 = Server.MapPath("~/relative");
Request.PhysicalPath
Server.MapPath is among the most used way to do it.
string physicalPath = Server.MapPath(Request.Url);
Server.MapPath( Request.AppRelativeCurrentExecutionFilePath )

Resources