if (!app.Environment.IsDevelopment()) { // do something }IWebHostEnvironment接口有3个方法判断宿主环境
if (!app.Environment.IsDevelopment()) { // 堆代码 duidaima.com // do something } if (app.Environment.IsStaging()) { // do something } if (!app.Environment.IsProduction()) { // do something }二. ASP.NET Core 设置宿主环境
{ "profiles": { "http": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, "applicationUrl": "http://localhost:5041" }, "https": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, "applicationUrl": "https://localhost:7034;http://localhost:5041" }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } }, "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:1894", "sslPort": 44305 } } }你也可以直接编辑json文件,不需要通过Properties页面来编辑环境变量,我们将https运行模式下ASPNETCORE_ENVIRONMENT修改为Production
"ASPNETCORE_ENVIRONMENT": "Production"我们将前面创建的中间件让它们在生产环境中执行
if (app.Environment.IsProduction()) { app.UseMiddleware<ResponseEditingMiddleware>(); app.UseMiddleware<RequestEditingMiddleware>(); app.UseMiddleware<ShortCircuitMiddleware>(); app.UseMiddleware<ContentMiddleware>(); }三. 在控制器中获取宿主环境&WebRootPath
namespace AspNetCore.Configuration.Controllers { public class SomeController : Controller { private IWebHostEnvironment _env; public SomeController(IWebHostEnvironment hostingEnvironment) { _env = hostingEnvironment; } public IActionResult Index() { if (_env.IsDevelopment()) { // do something } if (_env.IsStaging()) { // do something } if (_env.IsProduction()) { // do something } return View(); } } }IWebHostEnvironment 接口的WebRootPath属性指向应用程序静态文件目录wwwroot, 你可以在控制器中使用这个属性来获取文件的绝对路径
<img src="@ViewBag.ImagePath" alt="WebRootPath example" />
我们现在View的img标签上显示图片,使用ViewBag绑定scr属性
app.UseStaticFiles(); app.UseRouting();总结