【问题标题】:ASP.NET MVC Razor render without encoding没有编码的 ASP.NET MVC Razor 渲染
【发布时间】:2010-11-01 17:50:13
【问题描述】:

Razor 默认编码字符串。不编码渲染有什么特殊语法吗?

【问题讨论】:

    标签: c# .net asp.net asp.net-mvc razor


    【解决方案1】:

    从 ASP.NET MVC 3 开始,您可以使用:

    @Html.Raw(myString)
    

    【讨论】:

    • 这并不完全正确。是的,您可以插入原始字符串,但如果您有 "'<>etc...,这些将被转义。正确的方法是使用允许“非法”字符的 MvcHtmlString。例如,如果您正在编码 Json 数据......而不编码整个模型
    • Daniel, Html.Raw() "返回非 HTML 编码的标记。"
    • Html.Raw() 对引号进行编码..."myAttr='hello';myInt=10"
    • 它不对引号进行编码。除了明显的文档将其简单说明为 day(“此方法使用 IHtmlString 类包装 HTML 标记,它呈现 未编码 HTML。”)我还对此进行了测试,引号不是编码。
    【解决方案2】:
    @(new HtmlString(myString))
    

    【讨论】:

      【解决方案3】:

      除了已经提到的@Html.Raw(string) 方法,如果你输出一个 MvcHtmlString 它不会被编码。这在将您自己的扩展添加到 HtmlHelper 或从您知道可能包含 html 的视图模型返回值时很有用。

      例如,如果您的视图模型是:

      public class SampleViewModel
      {
        public string SampleString { get; set; }
        public MvcHtmlString SampleHtmlString { get; set; }
      }
      

      对于 Core 1.0+(和 MVC 5+)使用 HtmlString

      public class SampleViewModel
      {
        public string SampleString { get; set; }
        public HtmlString SampleHtmlString { get; set; }
      }
      

      然后

      <!-- this will be encoded -->
      <div>@Model.SampleString</div>
      <!-- this will not be encoded -->
      <div>@Html.Raw(Model.SampleString)</div>
      <!-- this will not be encoded either -->
      <div>@Model.SampleHtmlString</div>
      

      【讨论】:

        【解决方案4】:

        请谨慎使用@Html.Raw(),因为您可能会在编码和安全方面造成更多问题。我理解用例,因为我必须自己这样做,但要小心......只是避免允许所有文本通过。例如只保留/转换特定的字符序列并始终编码其余的:

        @Html.Raw(Html.Encode(myString).Replace("\n", "<br/>"))
        

        那么您就可以放心,您没有制造潜在的安全漏洞,并且任何特殊/外来字符都可以在所有浏览器中正确显示。

        【讨论】:

        • +1 正是我需要的!字符串仍然需要编码,但返回的行必须是 html。谢谢!
        • @Html.Raw(Html.Encode(myString).Replace(Html.Encode("\n"), "&lt;br/&gt;")) 用于 ASP.NET Core
        【解决方案5】:

        对于ActionLink,它一般在链接文本上使用HttpUtility.Encode。 在这种情况下 您可以使用 HttpUtility.HtmlDecode(myString) 当使用 HtmlActionLink 解码我想要传递的字符串时,它对我有用。例如:

          @Html.ActionLink(HttpUtility.HtmlDecode("myString","ActionName",..)

        【讨论】:

          【解决方案6】:

          你也可以使用 WriteLiteral 方法

          【讨论】:

            猜你喜欢
            • 2011-05-03
            • 2012-05-28
            • 2011-10-10
            • 1970-01-01
            • 2019-08-26
            • 1970-01-01
            • 2015-02-02
            • 2015-04-13
            • 1970-01-01
            相关资源
            最近更新 更多