How to leave URL parameters unescaped in ASP.NET MVC?

前端 未结 5 1553
猫巷女王i
猫巷女王i 2020-12-16 04:57

I\'ve noticed the returnurl URL parameter on the Stackoverflow login/logout links are not escaped but when I try to add path as a parameter to a route it gets escaped.

5条回答
  •  爱一瞬间的悲伤
    2020-12-16 05:02

    My solutionto a similar problem was to write my own extension. After digging around in the code I couldn't find a way to do it otherwise. Yours might look like this.

    public static class HtmlHelperExtensions
    {
        public static string LoginLinkWithReturnUrl( this HtmlHelper helper,
                                                     string linkText,
                                                     string action,
                                                     string controller,
                                                     string returnUrl,
                                                     object htmlAttributes )
        {
             TagBuilder builder = new TagBuilder("a");
             builder.Attributes.Add( "href",
                                      string.Format( "/{0}/{1}?returnurl={2}",
                                                     controller,
                                                     action,
                                                     returnUrl ) );
             var attrDict = new RouteValueDictionary( htmlAttributes );
             builder.MergeAttributes( attrDict );
             builder.InnerHtml = linkText;
             return builder.ToString();
        }
    }
    

    I think I had the same problem making and using a UrlHelper so I went with the string.Format mechanism instead. YMMV.

提交回复
热议问题