You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含Razor表达式的<link>标签以纯文本形式展示?

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 (&lt;, &gt;) 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:

&lt;link rel='stylesheet' href='@(Request.Url.AbsoluteUri + item.Path)' &gt;

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:

&lt;link rel='stylesheet' href='@(Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content(item.Path))' &gt;

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:12:14