web-dev-qa-db-ja.com

非静的フィールド、メソッド、またはプロパティ 'System.Web.UI.Page.Server.get'にはオブジェクト参照が必要です

したがって、2つの関数があり、興味深い問題が発生しています。基本的に、簡単にインクルードできる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( "./" +ファイル名);

9
user798080

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

または(静的であるように見せかけるので、それほど良いオプションではありませんが、webcontext呼び出しに対してのみ静的です):

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

私はしばらく前に同様のことに遭遇しました-単純に言えば、静的メソッド内の.csコードビハインドからServer.MapPath()をプルすることはできません(そのコードビハインドが何らかの形でWebページクラスを継承している場合を除きますが、おそらくそうではありませんとにかく許可されます)。

私の簡単な修正は、メソッドの背後にあるコードでパスを引数としてキャプチャし、呼び出し元のWebページが呼び出し中にServer.MapPathを使用してメソッドを実行することでした。

コードビハインド(.CS):


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

... now go do something ...
}

Webページ(.ASPX)メソッド呼び出し:


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

OPを打ち負かしたり話したりする必要はありません。それは正当な混乱のようでした。お役に立てれば ...

1
Chris

HttpContext.Currentの使用はどうですか?これを使用して、静的関数でServerへの参照を取得できると思います。

ここで説明: 静的クラスでアクセスされるHttpContext.Current

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


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