ASP.net MVC自定义字符串输出重载运算符<%=h

发布于 2024-07-06 16:26:28 字数 318 浏览 5 评论 0 原文

我目前正在制作一个新的 ASP.net MVC 网站,发现自己到处都在使用 Html.Encode,这是很好的做法,但变得非常混乱。 我认为清理这个问题的一个好方法是如果我可以重载一个运算符来自动进行 Html 编码。

以前:

<%= Html.Encode( ViewData['username'] ) %>

相当于:

<%=h ViewData['username'] %>

任何人都知道如何做到这一点,也许使用扩展方法或其他方法?

I am currently in the process of making a new ASP.net MVC website, and find myself using Html.Encode all over the place, which is good practice, but gets pretty messy. I think a good way to clean this up would be if I could overload an operator to automatically do Html encoding.

Previously:

<%= Html.Encode( ViewData['username'] ) %>

Would be equivalent to:

<%=h ViewData['username'] %>

Anyone have any ideas how I could do this, maybe using an extension method or something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

莫多说 2024-07-13 16:26:28

它不像运算符重载那么干净,但我使用了以下扩展方法:

public static string Safe(this string sz)
{
    return HttpUtility.HtmlEncode(sz);
}

所以在我的 aspx id do:

<%= this.ViewData["username"].Safe() %>

将额外的方法添加到表达式的末尾对我来说看起来比通过函数发送值更漂亮。

It's not so clean as an operator overload, but I used the following extension method:

public static string Safe(this string sz)
{
    return HttpUtility.HtmlEncode(sz);
}

So in my aspx id do:

<%= this.ViewData["username"].Safe() %>

Tacking the extra method onto the end of the expression just looks prettier to me than sending the value through a function.

悟红尘 2024-07-13 16:26:28

注意:这是一个丑陋且未经测试的黑客,我认为我永远不会这样做

public static String h (this System.Object o, System.Object viewData)
{
    return Html.Encode(viewData);
}

我不确定 ViewData 是什么类型,所以我在这里使用了 Object,最好实际上更改实际代码中的类型。

这是通过将扩展方法挂在 System.Object 上来实现的,因此它始终可用于所有类型......丑陋,但它可以完成工作:

<%=h(ViewData['username']) %>

NOTE: This is an ugly and untested hack, I don't think I'd ever do this

public static String h (this System.Object o, System.Object viewData)
{
    return Html.Encode(viewData);
}

I'm not sure what type ViewData is, so I used Object here, it would be best to actually change the type in the real code.

this works by hanging an extension method off System.Object, so it is always available on all types...ugly, but it may do the job:

<%=h(ViewData['username']) %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文