1. IWebHostEnvironment获取常用属性
(1).获取项目的根目录
_env.ContentRootPath 等价于 Directory.GetCurrentDirectory()
(2).获取项目下wwwroot目录
_env.WebRootPath
(3).获取项目最终dll的目录(拼接)
_env.ContentRootPath + @"\bin\Debug\netcoreapp3.1\"
(4).获取项目名称
_env.ApplicationName
(5).获取运行环境
_env.EnvironmentName
代码分享:
1 private IWebHostEnvironment _env; 2 3 public FirstController(IWebHostEnvironment env) 4 { 5 this._env = env; 6 } 7 8 public IActionResult Index() 9 {10 //1. 获取各种地址11 {12 //项目的绝对目录13 var d1 = _env.ContentRootPath;14 var d2 = Directory.GetCurrentDirectory();15 //项目的WebRoot目录16 var d3 = _env.WebRootPath;17 //最终dll文件的目录,拼接18 var d4 = _env.ContentRootPath + @"\bin\Debug\netcoreapp3.1\";19 //项目名称20 var d5 = _env.ApplicationName;21 //项目运行环境22 var d6 = _env.EnvironmentName;23 24 ViewBag.d1 = d1;25 ViewBag.d2 = d2;26 ViewBag.d3 = d3;27 ViewBag.d4 = d4;28 ViewBag.d5 = d5;29 ViewBag.d6 = d6;30 }31 return View();32 }
运行效果:
2. 获取内外网ip地址和端口
(1).获取请求的外网ip和端口:this.HttpContext.Connection.RemoteIpAddress; 和 this.HttpContext.Connection.RemotePort;
(2).获取本地内网ip和端口: this.HttpContext.Connection.LocalIpAddress; 和 this.HttpContext.Connection.LocalPort;
代码分享:
1 var p1 = this.HttpContext.Request.Method;2 //外网ip,必须部署在外网服务器上. Server-client如果在一个内网中,获取的还是内网地址3 var p2 = this.HttpContext.Connection.RemoteIpAddress;4 var p3 = this.HttpContext.Connection.RemotePort;5 6 //获取本地ip地址和端口,即项目部署在哪,获取的就是哪的。7 var p4 = this.HttpContext.Connection.LocalIpAddress;8 var p5 = this.HttpContext.Connection.LocalPort;