如何在位于虚拟路径中的应用程序启动时加载定义文件

时间:2010-06-28 08:16:46

标签: c# asp.net

如何在Application_Start中加载包含一些启动逻辑的定义文件?

我只知道虚拟路径,但不知道服务器物理路径。如何在没有Server.MapPath()

的情况下将虚拟路径转换为服务器路径

我不确定我是否可以在应用程序启动阶段访问httpcontext。

由于

2 个答案:

答案 0 :(得分:0)

  

“我不确定我是否可以在应用程序启动阶段访问httpcontext。”

您不能使用Request对象或HttpContext when you are using IIS7 or higherApplication_Start对象中的任何内容(但它确实适用于IIS6)。但是,可以使用Server.MapPath简单地获取物理应用程序路径,如下所示:

string physicalPath = Server.MapPath("~");

不确定为什么您不希望使用Server.MapPath,但这是以安全的方式获取位置的可靠方法,并且它在Application_Start中运行良好。

如你所知,正如我之前所说,你是cannot get the current context in Application_Start,因为不一定有。您仍然可以使用上面的Server.MapPath,或者,如果由于某种原因您不能使用Server.MapPath,则可以使用适用于所有地方的 HttpRuntime.AppDomainPath

string physicalPath = HttpRuntime.AppDomainPath;

答案 1 :(得分:0)

我认为对Application_Start方法和Global类本身存在一些误解。为每个请求创建一个Global类的新实例,但Application_Start方法仅在应用程序第一次运行时触发。

你可以从这里实际访问HttpContext.Current.Server属性:

var server = HttpContext.Current.Server;
string path = server.MapPath(...);