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?
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"]) %>
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.
FYI, the Microsoft Web Protection Library (A.K.A. Microsoft AntiXSS Library) developers seem to have broken the assembly and pulled all previous versions that were working. It is no longer a viable solution in its current state. I was looking at it as a solution for this problem before reading the comments. All 18 of the current ratings for the latest release are negative and complain about it being broken with no updates from the developers so I didn't even try it.
I went with @ICodeForCoffee's solution since I'm using Razor. It is simple and seems to work quite well. I needed to take potentially lengthy descriptions with line breaks and format them so the line breaks would come through in the page.
Just for completeness, here's the code I used which is @ICodeForCoffee's code modified to use the description field of the view's model:
@MvcHtmlString.Create(Html.Encode(Model.Description).Replace(Environment.NewLine, "<br />"))
"Process" the message in the controller:
- HTMLEncode the message
- Insert the line break tags
- Add message to the TempData collection.
Try this:
StringBuilder sb = new StringBuilder();
foreach(string message in messages)
{
sb.Append(string.Format("{0}<br />", Server.HtmlEncode(message));
}
TempData["message"] = sb.ToString();
来源:https://stackoverflow.com/questions/3858807/how-do-you-handle-line-breaks-in-html-encoded-mvc-view