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

标签 c# asp.net inheritance object server.mappath

所以我有两个函数,我遇到了一个有趣的问题。本质上,我的目标是使我的代码在易于包含的 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>

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

Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Server.get'

在下面一行:

Line 5: string path = Server.MapPath("./" + filename);

最佳答案

Server仅对 System.Web.UI.Page 实例可用(因为它是一个实例属性)。

你有两个选择:

  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;
}

或者(不是那个好的选择,因为它以某种方式伪装成静态的,而是仅对于 webcontext 调用是静态的):

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

关于c# - 非静态字段、方法或属性需要对象引用 'System.Web.UI.Page.Server.get',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10505187/

相关文章:

asp.net - 通过 jQuery 在 asp :LinkButton click event 上引发确认对话框

c++ - 从指向基类的指针调用派生类的复制构造?

c++ - 使用共享指针访问单例子类时出现 SEGFAULT

c# - Array.Copy 是否保证基于每个元素的原子读写?

c# - 如何在 iTextSharp\iText 中的两个元素之间添加空格\边距?

c# - 如何找出 ServiceHost Faulted 事件的原因

c# - 从 .Net v4.5 升级到 .Net v4.5.2 后未声明元素验证错误

c# - 如何从 Gridview 中获取行并将它们插入数据库?

c# - 从数据库中提取大量数据时出现内存不足异常

java - 接口(interface)允许任何子类参数