ASP.NET MVC Razor render without encoding

2019-01-06 13:44发布

Razor encodes string by default. Is there any special syntax for rendering without encoding?

7条回答
在下西门庆
2楼-- · 2019-01-06 14:04

Use @Html.Raw() with caution as you may cause more trouble with encoding and security. I understand the use case as I had to do this myself, but carefully... Just avoid allowing all text through. For example only preserve/convert specific character sequences and always encode the rest:

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

Then you have peace of mind that you haven't created a potential security hole and any special/foreign characters are displayed correctly in all browsers.

查看更多
做自己的国王
3楼-- · 2019-01-06 14:06

In case of ActionLink, it generally uses HttpUtility.Encode on the link text. In that case you can use HttpUtility.HtmlDecode(myString) it worked for me when using HtmlActionLink to decode the string that I wanted to pass. eg:

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

查看更多
乱世女痞
4楼-- · 2019-01-06 14:09
@(new HtmlString(myString))
查看更多
我只想做你的唯一
5楼-- · 2019-01-06 14:15

As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.

For example, if your view model was:

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

For Core 1.0+ (and MVC 5+) use HtmlString

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

then

<!-- 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>
查看更多
闹够了就滚
6楼-- · 2019-01-06 14:21

HTML RAW :

@Html.Raw(yourString)
查看更多
Deceive 欺骗
7楼-- · 2019-01-06 14:24

You can also use the WriteLiteral method

查看更多
登录 后发表回答