SoFunction
Updated on 2025-03-07

Summary of the problem of Url relative path

The most worrying thing is that sometimes absolute paths must be used (such as master content) because in the development process, without the target address, it is impossible to configure absolute paths. Sometimes relative paths are indeed necessary.

However, after writing the relative path, there are various problems.
Today, I will introduce you to two different methods.
First of all, the easiest thing to introduce is the new Base tag added in HTML5.
We look at its usage and must be included in the head tag.

Copy the codeThe code is as follows:

<head>
<base target="_blank" href="" />
</head>


The most important thing is that after the base tag is configured, the browser will no longer use the relative URL in the current document, but will use the specified base URL to parse all relative URLs.
Look at the above picture. If the URL in your <a>, <img>, <link>, and <form> tags is "", then the browser will automatically prepend the href address specified in the base tag when the link address is connected, and its opening method will also follow the target attribute set in the Base tag. Then in the future, we can set the base tag in master and mvc to solve the problem of absolute and relative paths that are troublesome. In the future, we can set all relative paths to start from the root of the website. Just configure the URL in Base to solve all the problems of relative and absolute paths.
For browsers that do not support html5, we can actually write a few codes using C# to get the address of the root directory of the website:
Copy the codeThe code is as follows:

public static string HostUrl()
{
String path = + "://" +
+
( == "/" ? "" : );
return path;
}


To sum up: you only need to use the "url + relative path" method to deal with problems caused by relative paths.
For example: /ab/
You can use the Base tag:
<head>
<base target="_blank" href="" />
</head>

The relative path is written as: <img src="ab/"/>
If using multiple C# to support it: HostUrl()+"ab/"