I am unsure of the best way to handle this. In my index view I display a message that is contained in TempData["message"]
. This allows me to display certain error or informational messages to the user when coming from another action (for example, if a user tries to enter the Edit action when they don't have access, it kicks them back to the Index with a message of "You are not authorized to edit this data").
Prior to displaying the message, I run Html.Encode(TempData["message"])
. However, I have recently come into the issue where for longer messages I want to be able to separate the lines out via line breaks (<br>
). Unfortunately (and obviously), the <br>
gets encoded by Html.Encode
so it doesn't cause an actual line break.
How do I process line breaks correctly in Html Encoded strings?
The easiest solution I've seen is:
@MvcHtmlString.Create(Html.Encode(TempData["message"]).Replace(Environment.NewLine, "<br />"))
If you are using a razor view, you should not have to call Html.Encode normally. By default, Razor html encodes all output. From Scott Gu's blog introducing Razor:
By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.
I agree with @Roger's comment - there is not really any need to encode anything that you have total control over.
If you still wish to be better safe than sorry (which isn't a bad thing), you could use the Microsoft AntiXss library and use the .GetSafeHtmlFragment(input)
method - see HTML Sanitization in Anti-XSS Library
e.g.
<%= AntiXss.GetSafeHtmlFragment(TempData["message"]) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With