123

検索クエリにLucene.Netを使用しているASP.NETMVCサイトを構築しています。ここで、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);

静的であるようwriterに、静的でIndexLocationなければなりません。したがって、コンパイラは次のエラーを表示しますServer.MapPath()

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

静的フィールドからServer.MapPath()または同様のものを使用する方法はありますか?このエラーを修正するにはどうすればよいですか?

4

2 に答える 2

247

を試してみてHostingEnvironment.MapPathくださいstatic

HostingEnvironment.MapPath次と同じ値を返す確認については、この SO の質問を参照してくださいServer.MapPath: Server.MapPath と HostingEnvironment.MapPath の違いは何ですか?

于 2010-09-25T23:58:25.877 に答える
53

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

于 2013-10-26T14:22:38.597 に答える