【问题标题】:Why can't I use HttpServerUtility.HtmlEncode inside a class?为什么我不能在类中使用 HttpServerUtility.HtmlEncode?
【发布时间】:2012-05-02 21:22:44
【问题描述】:

我正在尝试使用以下代码:

string myString = HttpServerUtility.HtmlEncode("my link & details");

我收到以下错误:

非静态字段、方法或属性需要对象引用。

为什么我不能在类中使用HttpServerUtility.HtmlEncode

【问题讨论】:

    标签: c# .net static encode


    【解决方案1】:

    您可以改用HttpUtility,它有一个不依赖于HttpContext 的静态方法。

    string myString = HttpUtility.HtmlEncode("my link & details");
    

    More info on HttpUtility.HtmlEncode method on the MSDN

    【讨论】:

    • 点赞!我有同样的问题,但没有 HttpContext 可以使用,所以这就是我的解决方案。
    • 这是更好的方法,你永远不知道你的 HttpContext.Current 什么时候会为空!
    【解决方案2】:

    HtmlEncode 不是静态方法,需要HttpServerUtility 的实例才能调用。由于 HttpContext.Current.Server 是一个 HttpServerUtility 实例,您可以改为使用;

    string myString = HttpContext.Current.Server.HtmlEncode("my link & details");
    

    【讨论】:

    • 是一样的。 HttpServerUtility.HtmlEncode 只是转发给 HttpUtility.HtmlEncode
    【解决方案3】:

    如果您使用的是 .NET 4.5,此实用程序是 System.Net.WebUtility 的一部分。

    string myString = System.Net.WebUtility.HtmlEncode(my link & details);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      相关资源
      最近更新 更多