1.获取完整网址URL
方法一:先引用“using Microsoft.AspNetCore.Http.Extensions;”,然后直接用“Request.GetDisplayUrl();”
方法二:后来参考 Microsoft.AspNetCore.Rewrite 的源代码,写了一个扩展方法实现
namespace Microsoft.AspNetCore.Http { public static class HttpRequestExtensions { public static string GetAbsoluteUri(this HttpRequest request) { return new StringBuilder() .Append(request.Scheme) .Append("://") .Append(request.Host) .Append(request.PathBase) .Append(request.Path) .Append(request.QueryString) .ToString(); } } }
2.获取网站在服务器的物理路径
public class HomeController : Controller { IHostingEnvironment env; public HomeController(IHostingEnvironment _env) { env = _env; } public IActionResult Index() { //https://localhost:44359/home/index string url = HttpContext.Request.GetDisplayUrl(); //D:\\Visual Studio 2017\\tourism_app\\ZhiRen.Tourism.UI\\bin\\Debug\\netcoreapp2.1\\ string path = System.AppContext.BaseDirectory; //D:\\Visual Studio 2017\\tourism_app\\ZhiRen.Tourism.UI string siteRoot = env.ContentRootPath; //D:\\Visual Studio 2017\\tourism_app\\ZhiRen.Tourism.UI\\wwwroot string wwwroot = env.WebRootPath; //D:\\Visual Studio 2017\\tourism_app\\ZhiRen.Tourism.UI\\bin\\Debug\\netcoreapp2.1 var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); return View(); } }
3.获取物理路径
string Paths = Path.GetFullPath("..");
4.ASP.NET总结C#中7种获取当前路径的方法
AppDomain.CurrentDomain.BaseDirectory=D:\lindexi\dotnet 获取程序所在路径的方法\ Environment.CurrentDirectory=D:\lindexi\dotnet 获取程序所在路径的方法 Assembly.GetCallingAssembly().Location=D:\lindexi\dotnet 获取程序所在路径的方法\SetereBojerhis.exe Assembly.GetEntryAssembly().Location=D:\lindexi\dotnet 获取程序所在路径的方法\SetereBojerhis.exe Assembly.GetExecutingAssembly().Location=D:\lindexi\dotnet 获取程序所在路径的方法\SetereBojerhis.exe Directory.GetCurrentDirectory()=D:\lindexi\dotnet 获取程序所在路径的方法 AppDomain.CurrentDomain.SetupInformation.ApplicationBase=D:\lindexi\dotnet 获取程序所在路径的方法\ Process.GetCurrentProcess().MainModule.FileName=D:\lindexi\dotnet 获取程序所在路径的方法\SetereBojerhis.exe