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

懵懂的女人 提交于 2019-12-05 02:28:05

Server is only available to instances of System.Web.UI.Page-implementations (as it's an instance property).

You have 2 options:

  1. Convert the method from static to instance
  2. Use following code:

(overhead of creating a 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;
}

or (not tested):

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

or (not that good option, as it somehow fakes to be static but rather is static for webcontext-calls only):

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

What about using HttpContext.Current? I think you can use that to get a reference to Server in a static function.

Described here: HttpContext.Current accessed in static classes

I ran into a similar thing some time back -- put simply you can't pull Server.MapPath() from the .cs code-behind inside a static method (unless that code behind somehow inherits a web page class, which is probably not allowed anyway).

My simple fix was to have the code behind method capture the path as an argument, then the calling web page executes the method with Server.MapPath during the call.

Code Behind (.CS):


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

... now go do something ...
}

Web-Page (.ASPX) Method Call:


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

No need to bash or talk down to the OP, it seemed a legitimate confusion. Hope this helps ...

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


includer(Server.MapPath("./" + filename));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!