Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从当前服务器请求资源(相对路径)?_C#_Asp.net - Fatal编程技术网

C# 如何从当前服务器请求资源(相对路径)?

C# 如何从当前服务器请求资源(相对路径)?,c#,asp.net,C#,Asp.net,如果我需要从当前服务器获取相对路径。以下内容无效,因为它不是有效的URI var request = WebRequest.Create("\path_to_resource") 我相信最简单的方法是将路径放在web.config中,但是,当应用程序移动到另一台服务器时,忘记更新配置很容易破坏这一点。有比这更好的方法吗 var request = WebRequest.Create(ConfigurationManager.AppSettings["root"] + "\path_to_res

如果我需要从当前服务器获取相对路径。以下内容无效,因为它不是有效的URI

var request = WebRequest.Create("\path_to_resource")
我相信最简单的方法是将路径放在web.config中,但是,当应用程序移动到另一台服务器时,忘记更新配置很容易破坏这一点。有比这更好的方法吗

var request = WebRequest.Create(ConfigurationManager.AppSettings["root"] + "\path_to_resource");

好吧,你可以用这样的东西:

private string CurrentDomain()
{
    string currDomain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host;
    if (Request.Url.Port != 80 && Request.Url.Port != 443)
        currDomain += (":" + Request.Url.Port);
    return currDomain;
}
使用这些不同的对象属性将为您提供当前域名,您可以将资源的子文件夹附加到该域名上

Request.Url.Scheme
是Url的
http/https
部分,
System.Uri.schemedelimitor
:///code>部分,
Request.Url.Host
将是您的实际主机名(即
example.com
)。
如果您的站点运行在非标准端口上,则对
Request.Url.port
的调用也会将其添加到Url“域名”中。
请注意,这不是防弹代码,因为它假定您(例如)在默认端口443上运行SSL(https)

如果需要实际的物理文件路径,可以使用来检索ASP.NET应用程序“根”的物理文件路径,并从中附加子文件夹


另请参见:

如果应用程序不在域的根目录下,该怎么办?如果应用程序不在域的根目录下,则可以使用:Request.ApplicationPath。所以“CurrentDomain()+Request.ApplicationPath+”/MyPage.aspx”