Microsoft Web API:你如何做一个 Server.MapPath? [英] Microsoft Web API: How do you do a Server.MapPath?
问题描述
由于 Microsoft Web API 不是 MVC,你不能做这样的事情:
Since Microsoft Web API isn't MVC, you cannot do something like this:
var a = Request.MapPath("~");
也不是这个
var b = Server.MapPath("~");
因为它们在 System.Web
命名空间下,而不是在 System.Web.Http
命名空间下.
because these are under the System.Web
namespace, not the System.Web.Http
namespace.
那么你如何在 Web API 中找出相对服务器路径?
我曾经在 MVC 中做这样的事情:
So how do you figure out the relative server path in Web API ?
I used to do something like this in MVC:
var myFile = Request.MapPath("~/Content/pics/" + filename);
哪个会给我磁盘上的绝对路径:
Which would give me the absolute path on disk:
"C:inetpubwwwrootmyWebFolderContentpicsmypic.jpg"
推荐答案
您可以使用 HostingEnvironment.MapPath 在 System.Web
对象(如 HttpContext.Current
)不可用的任何上下文中(例如,也来自静态方法).
You can use HostingEnvironment.MapPath in any context where System.Web
objects like HttpContext.Current
are not available (e.g also from a static method).
var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SomePath");
另见服务器之间的区别是什么.MapPath 和 HostingEnvironment.MapPath?
这篇关于Microsoft Web API:你如何做一个 Server.MapPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!