C# HTML 字符串显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8982911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# HTML String Display
提问by Syed Salman Raza Zaidi
I am making an application in MVC3, i am storing a string in database in this format
我正在 MVC3 中创建一个应用程序,我正在以这种格式在数据库中存储一个字符串
<a href='path'>Text</a> Happy
The field is saving properly but i have to display it in web page with hyper link like
该字段正在正确保存,但我必须使用超链接将其显示在网页中
TextHappy
文字快乐
but currently it is showing like
但目前它显示为
<a href='path'>Text</a> Happy
How can i render this string as HTML on web page?
如何在网页上将此字符串呈现为 HTML?
采纳答案by sblom
If you're using the Razor template engine:
如果您使用 Razor 模板引擎:
@Html.Raw(mystring)
回答by CCBlackburn
If you are using Razor you can use @Html.Raw()as per Phil Haack's quick reference
如果您使用 Razor,您可以@Html.Raw()按照 Phil Haack 的快速参考使用
回答by alun
I would really advice against doing that because it's very hard to guard against script injection problems.
我真的建议不要这样做,因为很难防止脚本注入问题。
That being said though, if you think that can be managed, you should be able to use @Html.Raw to render the text without escaping.
尽管如此,如果您认为可以管理,您应该能够使用 @Html.Raw 来呈现文本而不会转义。
回答by perfectionist
If you are not using razor,
如果你不使用剃须刀,
and string text = "<a href='path'>Text</a> Happy";
和 string text = "<a href='path'>Text</a> Happy";
Then you want <%= text %>, not <%: text %>
那么你想要<%= text %>,而不是<%: text %>
As others have said, this is not considered great practice due to HTML injection, but it seems HTML injection is your intention.
正如其他人所说,由于 HTML 注入,这不是很好的做法,但似乎 HTML 注入是您的意图。
回答by casper123
its better you Encode HTML before storing it to database.. If you're using .Net Framework 4 try this
最好在将 HTML 存储到数据库之前对其进行编码。如果您使用的是 .Net Framework 4,请尝试此操作
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);
See msdn
见msdn
Otherwise use anti xss library
否则使用反 xss 库
Its workes like a magic and really easy to implement.. Un-Encoded is not only dangerous as it can cause XSS attacks but it also causes problems with rendering on html fornt page.
它的作用就像魔法一样,而且非常容易实现。未编码不仅危险,因为它会导致 XSS 攻击,而且还会导致在 html fornt 页面上呈现问题。
Hope it helps..
希望能帮助到你..

