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

9 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();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

这是引用它的页面:

<% @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>
Run Code Online (Sandbox Code Playgroud)

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

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

在以下行:

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

And*_*air 9

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

你有2个选择:

  1. 将方法从static转换为instance
  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;
}
Run Code Online (Sandbox Code Playgroud)

或(未经测试):

public static string FooMethod(string path)
{
    var mappedPath = HostingEnvironment.MapPath(path);
    return mappedPath;
}
Run Code Online (Sandbox Code Playgroud)

或者(不是那个好的选择,因为它以某种方式假装为静态,而只是静态的webcontext-calls):

public static string FooMethod(string path)
{
    var mappedPath = HttpContext.Current.Server.MapPath(path);
    return mappedPath;
}
Run Code Online (Sandbox Code Playgroud)