cshtmlで変数の改行を出力する

はじめに答え
@Html.Raw(Html.Encode("hello\r\nworld").Replace("&#xD;&#xA;", "<br>"))

hello
world

 

やっていること

  1. Html.Encode(変数)で、文字をエスケープする(XSS対策)
  2. Replace(“&#xD;&#xA;”, “<br>”)で、改行コードを<br>に置き換える。
  3. @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>")

xss-picture

 

なので、エスケープ処理Html.Encode()と組み合わせて使う

@Html.Raw(Html.Encode("hello\r\nworld").Replace("&#xD;&#xA;", "<br>"))

hello
world

コメント

タイトルとURLをコピーしました