非静态字段、方法或属性“System.Web.UI.Page.Server.get”需要对象引用

本文关键字:Server Page UI get 对象引用 Web System 字段 静态 方法 属性 | 更新日期: 2023-09-27 18:33:29

所以我有两个函数,我遇到了一个有趣的问题。从本质上讲,我的目标是使我的代码在易于包含的cs文件中更具可移植性。

这是说的cs文件:

namespace basicFunctions {
public partial class phpPort : System.Web.UI.Page {
    public static string includer(string filename) {
        string path = Server.MapPath("./" + filename);
        string content = System.IO.File.ReadAllText(path);
        return content;
    }
    public void returnError() {
        Response.Write("<h2>An error has occurred!</h2>");
        Response.Write("<p>You have followed an incorrect link. Please double check and try again.</p>");
        Response.Write(includer("footer.html"));
        Response.End();
    }
}
}

这是引用它的页面:

<% @Page Language="C#" Debug="true" Inherits="basicFunctions.phpPort" CodeFile="basicfunctions.cs" %>
<% @Import Namespace="System.Web.Configuration" %>
<script language="C#" runat="server">
void Page_Load(object sender,EventArgs e) {
    Response.Write(includer("header.html"));
    //irrelevant code
    if ('stuff happens') {
        returnError();
    }
    Response.Write(includer("footer.html"));
}
</script>

我得到的错误是上面列出的错误,即:

编译器错误消息:CS0120:非静态字段、方法或属性"System.Web.UI.Page.Server.get"需要对象引用

在以下行:

第 5 行:字符串路径 = Server.MapPath("./" + 文件名);

非静态字段、方法或属性“System.Web.UI.Page.Server.get”需要对象引用

Server仅适用于System.Web.UI.Page -实现的实例(因为它是实例属性)。

您有 2 个选项:

  1. 将方法从静态转换为实例
  2. 使用以下代码:

(创建System.Web.UI.HtmlControls.HtmlGenericControl的开销)

public static string FooMethod(string path)
{
    var htmlGenericControl = new System.Web.UI.HtmlControls.HtmlGenericControl();
    var mappedPath = htmlGenericControl.MapPath(path);
    return mappedPath;
}

或(未测试):

public static string FooMethod(string path)
{
    var mappedPath = HostingEnvironment.MapPath(path);
    return mappedPath;
}

或者(不是那个好的选择,因为它以某种方式假装是静态的,而是仅用于网络上下文调用的静态):

public static string FooMethod(string path)
{
    var mappedPath = HttpContext.Current.Server.MapPath(path);
    return mappedPath;
}

使用HttpContext.Current怎么样?我认为您可以使用它来获取对静态函数中Server的引用。

描述如下:在静态类中访问的 HttpContext.Current

前段时间我遇到了类似的事情——简单地说,你不能从静态方法中的.cs代码隐藏中提取 Server.MapPath()(除非该代码隐藏以某种方式继承了一个网页类,这可能是不允许的)。

我的简单解决方法是让方法背后的代码将路径捕获为参数,然后调用网页在调用期间使用 Server.MapPath 执行该方法。

代码隐藏 (.CS):


public static void doStuff(string path, string desc)
{
    string oldConfigPath=path+"webconfig-"+desc+"-"+".xml";
... now go do something ...
}

网页 (.ASPX) 方法调用:


...
doStuff(Server.MapPath("./log/"),"saveBasic");
...

无需抨击或与OP交谈,这似乎是一种合理的混乱。 希望这有帮助...

public static string includer(string filename) 
{
        string content = System.IO.File.ReadAllText(filename);
        return content;
}

includer(Server.MapPath("./" + filename));