9

だから私は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 行目: string path = Server.MapPath("./" + filename);

4

4 に答える 4

10

ServerSystem.Web.UI.Page-implementsのインスタンスでのみ使用できます(インスタンスプロパティであるため)。

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;
}
于 2012-05-08T19:31:52.293 に答える
1

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

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

于 2012-05-08T21:23:30.670 に答える
0
public static string includer(string filename) 
{
        string content = System.IO.File.ReadAllText(filename);
        return content;
}


includer(Server.MapPath("./" + filename));
于 2012-05-08T19:36:57.363 に答える