在ASP.NET MVC中的静态字段内使用Server.MapPath()

Max*_*sky 114 c# asp.net-mvc static lucene.net server.mappath

我正在构建一个ASP.NET MVC站点,我正在使用Lucene.Net进行搜索查询.我在这里问了一个关于如何在ASP.NET MVC应用程序中正确构建Lucene.Net用法的问题,并被告知最好的方法是将my声明IndexWriterpublic static,以便可以重用它.

以下是我的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);
Run Code Online (Sandbox Code Playgroud)

由于writer是静态的,IndexLocation也必须是静态的.因此,编译器给出了以下错误Server.MapPath():

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

没有办法在静态字段中使用Server.MapPath()或类似的东西?我该如何解决这个错误?

Jef*_*ata 235

试试HostingEnvironment.MapPath,这是static.

请参阅此SO问题进行确认,HostingEnvironment.MapPath返回相同的值Server.MapPath: Server.MapPath和HostingEnvironment.MapPath之间有什么区别?


pan*_*rma 42

我想你可以试着从课堂上打电话

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
Run Code Online (Sandbox Code Playgroud)

*----------------抱歉我疏忽了,因为静态功能已经通过adrift 回答了问题*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Run Code Online (Sandbox Code Playgroud)

更新

我在使用时遇到异常 System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex详细信息:System.ArgumentException:此处不允许使用相对虚拟路径"SignatureImages".在System.Web.VirtualPath.FailIfRelativePath()

解决方案(在静态web方法中测试)

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