MVC双重编码MvcHtmlString

时间:2013-05-30 18:10:39

标签: c# asp.net-mvc asp.net-mvc-routing

警告:我有一个MVC站点作为.Net WebForms站点中的一个区域。我正在提前解释它可以解释我的问题。

现在我遇到的问题是我正在路由可能包含特殊字符的值,例如apostrophe(单引号)。如果我没有对它正确路由的值进行编码,那么当使用未编码的单引号作为过滤器时,我的Kendo MVC Grid会创建一个无效的模板。

http://{base}/{area}/{controller}/{view}?customerName=Justin's%20Instance - Throws Invalid Template Error

http://{base}/{area}/{controller}/{view}?customerName=Justin's%20Instance - No Error

所以我认为最简单的解决方案是在将其作为路由值传递之前正确编码我的querystring参数。这导致了双重编码情况。然后我发现了MvcHtmlString.Create,它专门用于告诉路由系统不要重新编码字符串值。但是,它仍然是双重编码。

var customerNameEncoded = MvcHtmlString.Create(HttpUtility.HtmlEncode(model.Name));

var routeResult = RedirectToAction("ManageCustomer", new { customerName = customerNameEncoded });

return routeResult;

这是创建的网址:

http://{base/{area}/{controller}/{view}?customerName=Justin%26%2339%3Bs%20Instance

正如您所看到的那样'正在重新编码。这会引发以下错误。

> System.Web.HttpRequestValidationException   A potentially dangerous
> Request.QueryString value was detected from the client
> (customerName="Justin's Instance").

MVC区域的web.config具有以下标记:validateRequest="false"

整个网站的web.config具有以下内容:httpRuntime requestValidationMode="2.0"

关于为什么这个字符串被双重编码以及如何阻止它这样做的任何想法?

2 个答案:

答案 0 :(得分:0)

这里混合了两种不同类型的编码。 一个是HTML编码,它创建了那些& 39;逃逸序列。 其次是URL编码,它使%20转义序列。

我不知道Kendo MVC Grid是什么,我想我知道你的行动的结果应该是什么。试试这段代码

    public ActionResult Index()
    {
        var customerNameEncoded = "Justin's Instance";
        var url = Url.Action("ManageCustomer", new { customerName = customerNameEncoded });
        return Redirect(url);
    }

    public ActionResult ManageCustomer(string customerName)
    {
        ViewBag.CustomerName = customerName;
        return View();
    }

如果在返回之前停止Index方法,则会看到该网址内容为

"/Home/ManageCustomer?customerName=Justin%27s%20Instance"

正确编码的URL是什么。

您还可以在ManageCustomer操作中检查您获得的customerName,并且您将看到它

"Justin's Instance"

不要对您在浏览器的地址栏中看到的内容感到困惑。某些浏览器(如Firefox)不显示编码的URL,可能会显示“... / ManageCustomer?customerName = Justin's Instance”

答案 1 :(得分:0)

1)查询字符串参数是URL编码的,而不是HTML编码的。 (%表示法,而不是&#个实体)

2)配置设置validateRequestrequestValidationMode适用于ASP.Net WebForms,而不适用于MVC。您必须将[ValidateInput(false)]属性添加到控制器方法中,正如Bryan所评论的那样。