如何将含Razor表达式的<link>标签以纯文本形式展示?
<link> tag as plain text with full absolute URL Looks like you want to display a fully rendered <link> tag as plain text (so browsers show the tag itself instead of parsing it) while populating the href with a full absolute URL from your Razor view. Here are two straightforward ways to make this work:
Method 1: Manual HTML Entity Escaping
The simplest approach is to replace angle brackets (<, >) with their HTML entity equivalents (<, >) directly in your view. Razor will still process the @(...) expression to inject the actual URL, and the escaped brackets will ensure the tag displays as plain text instead of being parsed by the browser:
<link rel='stylesheet' href='@(Request.Url.AbsoluteUri + item.Path)' >
Quick fix for URL formatting
If Request.Url.AbsoluteUri includes a trailing slash (e.g., http://example.com/), combining it with item.Path (like css/a.min) might create a double slash in the final URL. To avoid this, use Request.Url.GetLeftPart(UriPartial.Authority) to get the base URL without a trailing slash, paired with Url.Content to resolve relative paths cleanly:
<link rel='stylesheet' href='@(Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content(item.Path))' >
Method 2: Server-Side Encoding (Better for Complex Scenarios)
For more control, build the full tag string on the server, encode it to escape HTML entities, then render it raw so the browser displays the plain text:
First, add a using directive for System.Web (if it’s not already present) to access HttpUtility:
@using System.Web
Then build and render the tag:
@{ // Build a clean full absolute URL var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority); var fullStylesheetUrl = baseUrl + Url.Content(item.Path); // Create the complete <link> tag string var linkTag = $"<link rel='stylesheet' href='{fullStylesheetUrl}' >"; } // Encode the tag to escape HTML entities, then render it raw @Html.Raw(HttpUtility.HtmlEncode(linkTag))
Either method will output exactly what you’re targeting:
<link rel='stylesheet' href='http://example.com/css/a.min' >
displayed as plain text in the browser.
内容的提问来源于stack exchange,提问作者americanslon

