C# get url, domain, absolute, relative and physical path

Lionsure 2020-07-24 Original by the website

The Request object is used to get various paths of Url in C#, including the Url of previous page, domain name, absolute path, relative path and physical path. Although in some cases, the Url cannot be got, it can be got in most cases, as described below.


1. C# Get the Url of current and previous page

(1) C# get current url: HttpContext.Current.Request.Url.PathAndQuery;

Note: The meaning of PathAndQuery is already obvious, that is, take the path and parameters(i.e. the full path), and you will get what is displayed in the address bar of the browser.


(2) C# get previous url: Page.Request.UrlReferrer;

Note: Referrer means the previous page.


(3) Note: If the current page is navigated by the Javascript of previous page, the Url cannot be got through the above methods, but it can be saved in Cookies.


2. C# get domain from url(C# get current domain name)

Use statement: Request.Url.Host;

Note: Only get the domain name part of the Url.


3. Get the absolute(full) Url

Use statement: Request.Url.AbsoluteUri;

Note: Absolute means sheer. Knowing the meaning is easy to understand, that is, you can get what is displayed in the browser address bar.


4. C# get absolute path from url

Use statement: Request.RawUrl;(Request.Url.PathAndQuery;) and Request.Url.AbsolutePath;

Note: raw means incomplete, RawUrl means to get the path other than the domain name, such as /ie/index.aspx; PathAndQuery and AbsolutePath are the same.


HttpContext.Current.Request.Url.Query;(Only get the parameters of Url, such as domain name/pub/Item.aspx?type=ie, the result is ?type=ie)


5. How to get path of file in c#

Request.CurrentExecutionFilePath;, Request.FilePath; and Request.Path;

Note: CurrentExecutionFilePath means the path of current execution file, FilePath means the file path; no matter which one is used, the result got is the same, that is, the file path except the domain name, such as /ie/index.aspx.


6. How to get physical path of file in c#

1. Use statement: Request.PhysicalApplicationPath;

Note: PhysicalApplicationPath means the physical application path, that is, the physical path of the disk where the root directory of the website is got. If the website is placed in the d:\webhost\ directory, it will be d:\webhost\.


2. Use statement: Request.PhysicalPath;

Note: PhysicalPath means the physical path, that is, the physical path to get the currently accessed webpage. If the website is placed in the d:\webhost\ directory and the currently accessed webpage is the homepage(index.aspx), then the got is d:\webhost\index.aspx.


3. Use statement: Request.ApplicationPath;

Note: ApplicationPath means the application path, that is, to get the root directory of the currently visited webpage. If the currently visited webpage is /ie/index.aspx and /word/index.aspx, you will get /.