Asp.Net MVC之防止用户注入脚本参数

假设有一个Controller,代码如下:

public string Browse(string genre)
{
    string message = "Store.Browse, Genre = " + genre;
    return message;
}

当用户输入http://localhost:5412/Store/Browse?genre=<script>window.location='https://www.baidu.com'<script>的时候会执行参数中的脚本。

为了阻止用户向视图中注入JS脚本或者HTML标记,需要把代码改成下面这样:

public string Browse(string genre)
{
    string message = HttpUtility.HtmlEncode("Store.Browse, Genre = " + genre);
    return message;
}

使用HttpUtility.HtmlEncode可以预处理用户输入。