Using Server.MapPath() inside a static field in ASP.NET MVC
Asked Answered
G

2

126

I'm building an ASP.NET MVC site where I'm using Lucene.Net for search queries. I asked a question here about how to properly structure Lucene.Net usage in an ASP.NET MVC application and was told that the best method is to declare the my IndexWriter as public static, so that it can be re-used.

Here is some code that is at the top of my SearchController:

public static string IndexLocation = Server.MapPath("~/lucene");
public static Lucene.Net.Analysis.Standard.StandardAnalyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer();
public static IndexWriter writer = new IndexWriter(IndexLocation,analyzer);

As writer is static, IndexLocation must also be static. Thus, the compiler is giving me the following error for Server.MapPath():

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

Is there a way of using Server.MapPath() or something similar from a static field? How can I fix this error?

Guaiacum answered 25/9, 2010 at 23:32 Comment(0)
C
254

Try HostingEnvironment.MapPath, which is static.

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

Clayton answered 25/9, 2010 at 23:58 Comment(2)
This function gave me an error as the result returbed by HostingEnvironment.MapPath is not the same as Server.MapPath, the latter returns an absolute url not a relative urlAdalineadall
@john, I get the same value for both.Handmedown
G
56

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Gauldin answered 26/10, 2013 at 14:22 Comment(1)
The only time I saw the error you mentioned in your update is when the code used a relative virtual path. For example, Server.MapPath() allows a path of "files/file1.doc". It uses the current context to determine the path of the current page, for example, and then creates the relative path from there. If we are in ~/Subfolder/Page1.aspx, the url would map from ~/Subfolder/files/file1.doc. The HostingEnviornment.MapPath() is static, and thus always requires the full virtual path, starting with the ~/ part of the url.Handmedown

© 2022 - 2024 — McMap. All rights reserved.