C# Server.MapPath 和 HostingEnvironment.MapPath 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/944219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:55:21  来源:igfitidea点击:

What is the difference between Server.MapPath and HostingEnvironment.MapPath?

c#asp.net

提问by empi

Is there any difference between Server.MapPath()and HostingEnvironment.MapPath()? Does Server.MapPath()have any advantages over HostingEnvironment.MapPath()?

有什么区别Server.MapPath()HostingEnvironment.MapPath()?是否Server.MapPath()有在任何优势HostingEnvironment.MapPath()

My original problem was mapping the file path on a server when the HttpContextis not present and I cannot pass a Servervariable from Global.asaxto my method.

我最初的问题是在HttpContext不存在的情况下映射服务器上的文件路径,并且我无法将Server变量传递Global.asax给我的方法。

I used HostingEnvironment.MapPath()instead since it doesn't need HttpContext. Are there any situations when these two methods will give different results?

HostingEnvironment.MapPath()改用了,因为它不需要HttpContext. 是否存在这两种方法会给出不同结果的情况?

采纳答案by Philippe Leybaert

Server.MapPath()eventually calls HostingEnvironment.MapPath(), but it creates a VirtualPathobject with specific options:

Server.MapPath()最终调用HostingEnvironment.MapPath(),但它会创建一个VirtualPath具有特定选项的对象:

The VirtualPathobject passed to HostingEnvironment.MapPath()is constructed like this:

VirtualPath.Create(path, VirtualPathOptions.AllowAllPath|VirtualPathOptions.AllowNull);

VirtualPath传递给的对象HostingEnvironment.MapPath()是这样构造的:

VirtualPath.Create(path, VirtualPathOptions.AllowAllPath|VirtualPathOptions.AllowNull);

Edit: in reality, the only difference is that you are allowed to pass null to Server.MapPath(), but not to HostingEnvironment.MapPath()

编辑:实际上,唯一的区别是您可以将 null 传递给Server.MapPath(),但不能传递给HostingEnvironment.MapPath()

回答by Mark Struzinski

Server.MapPath()requires an HttpContext. HostingEnvironment.MapPathdoes not.

Server.MapPath()需要一个HttpContext. HostingEnvironment.MapPath才不是。