Does ASP.NET MVC razor view engine encode HTML by default?
Does ASP.NET MVC razor view engine encode HTML by default?
Does ASP.NET MVC razor view engine encode HTML by default?
Or do we have to use the htmlhelpers
for html encoding the data.
回答
Yes it does. Use @Html.Raw(...)
to break that behavior.
Do I need to encode attribute values in MVC Razor?
Razor performs HTML encoding on strings by default. Depending on where your string is being injected into the HTML stream, this may or may not be the correct encoding to use. If it's not the correct encoding, then you need to perform the correct encoding yourself and be sure to return an MvcHtmlString (i.e. an IHtmlString) to ensure Razor leaves your custom encoding alone.
Since Razor uses HTML encoding, which is technically different from HTML attribute encoding (it's a subset), it's not wrong to use @Html.Raw(Html.AttributeEncode(Model.Value)) to HTML attribute encode the value. At the same time, it's also not necessary, since the default HTML encoding uses the same basic format and will just end up encoding a couple character that otherwise wouldn't need encoded in an HTML attribute value.
On the other hand, in the final case where a string is being injected into the quotes of a JavaScript string, the HTML encoding would absolutely be incorrect, so you'd definitely need to perform the encoding yourself as I did: @Html.Raw(HttpUtility.JavaScriptStringEncode(Model.Value)).
在Razor中输出Html的两种方式
Razor中所有的Html都会自动编码,这样就不需要我们手动去编码了(安全),但在需要输出Html时就是已经转义过的Html文本了,如下所示:
@{
string thisTest = "<span style=\"color:#f00;\">qubernet</span>";
}
@thisTest;
这样在页面输出的文本就是:<span style=\"color:#f00;\">qubernet</span>而不是红色的字体了,要输出红色的字体,有下面常用的两种方式:
1. 使用Razor中的Html.Raw(推荐使用这种方式):
@{
string thisTest = "<span style=\"color:#f00;\">qubernet</span>";
}
@Html.Raw(thisTest);
2. 使用MvcHtmlString类来实现:
@{
string thisTest = "<span style=\"color:#f00;\">qubernet</span>";
var thisResult = new MvcHtmlString(thisTest);
}
@thisResult或@(new HtmlString(thisTest))
@Html.Raw()
@Html.Raw() 方法输出带有html标签的字符串,如:
@Html.Raw("<div
style='color:red'>输出字符串</div>")
结果:输出字符串
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-09-03 Resize image online 调整图片大小
2019-09-03 Resend a Request by fiddler
2019-09-03 .NET Standard
2016-09-03 git -C
2016-09-03 Common Macros for Build Commands and Properties
2016-09-03 Hearthstone-Deck-Tracker项目的编译
2014-09-03 TeeChart的网络资料