zony.me

ASP.Net Core 获得网站根目录

一、ASP.Net

C#
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var _path = Server.MapPath("~/");
        return Content(_path);
    }
}

二、ASP.Net Core

C#
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace MyWebsite.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public HomeController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public ActionResult Index()
        {
            return Content($"WebRootPath = {_hostingEnvironment.WebRootPath}\n" +
                           $"ContentRootPath = {_hostingEnvironment.ContentRootPath}");
        }
    }
}

2.1 cshtml View 中使用

C#
@using Microsoft.AspNetCore.Hosting
@inject IHostingEnvironment hostingEnvironment

WebRootPath = @hostingEnvironment.WebRootPath <br />
ContentRootPath = @hostingEnvironment.ContentRootPath
ASP.Net Core 获得网站根目录
作者 Zony · 发布于 2017-10-16
Licensed under CC BY-NC-SA 4.0
← 上一篇ABP Code First 无法进行数据库迁移问题下一篇 →OneDriver 指定文件夹同步
目录