はじめに答え
@Html.Raw(Html.Encode("hello\r\nworld").Replace("
", "<br>"))
hello
world
やっていること
- Html.Encode(変数)で、文字をエスケープする(XSS対策)
- Replace(“
”, “<br>”)で、改行コードを<br>に置き換える。
- @Html.Raw()で、そのまま出力する
経緯
.cshtmlファイルで変数の内容を、htmlに文字出力するとき、@(変数)という書き方ができる。
@("hello world")
hello world
xssの心配もない
@("<script>alert('hello')</script>")
<script>alert(‘hello’)</script>
ところで、改行したいのだけれど
@("hello\r\nworld") @("hello<br>world")
hello world
hello<br>world
ちゃんと文字になってしまう。
@()ではどうやらエスケープされてうまく出力できない。
そこで、@Html.Raw()を使う。
htmlとして出力してくれるメソッドだ。
でも、XSSがこわい。
@Html.Raw("<script>alert('hello')</script>")
なので、エスケープ処理Html.Encode()と組み合わせて使う
@Html.Raw(Html.Encode("hello\r\nworld").Replace("
", "<br>"))
hello
world
コメント