How do you handle line breaks in HTML Encoded MVC view?

 ̄綄美尐妖づ 提交于 2019-12-01 06:14:15
Charlino

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"]) %>
ICodeForCoffee

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:

  1. HTMLEncode the message
  2. Insert the line break tags
  3. Add message to the TempData collection.
Andy Evans

Try this:

StringBuilder sb = new StringBuilder();

foreach(string message in messages)
{
sb.Append(string.Format("{0}<br />", Server.HtmlEncode(message));
}

TempData["message"] = sb.ToString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!