2016年12月1日 星期四

ASP.NET Core沒有Server.MapPath

 

Tool:Visual Studio 2015 Ultimate Update 3
OS:Windows 10
.NET Core  1.0.0
ASP.NET Core 1.0.0

掰,ASP.NET Core沒有Server.MapPath可用了。

如果想要在ASP.NET Core做到如Server.MapPath的效果,取得網站程式執行的資料夾位置,現在得透過IHostingEnvironment。

使用VS建立一個ASP.NET Core範本專案,預設網站專案結構大約如下:

image

撰寫Controller如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;

namespace CoreWebSample.Controllers
{
    public class HomeController : Controller
    {
        private IHostingEnvironment _he;
        public HomeController(IHostingEnvironment he)
        {
            _he = he;
        }
        public IActionResult Index()
        {
            ViewBag.wrp = _he.WebRootPath;
            ViewBag.crp = _he.ContentRootPath;
            return View();
        }
    }
}

Index View

Web Root Path : @ViewBag.wrp
<br/>
Content Root Path : @ViewBag.crp

 

WebRootPath屬性將取得wwwroot資料夾;ContentRootPath屬性將取得專案根目錄:

image

 

ContentRootPath屬性是來自於Program.cs檔案中,預設範本程式的設定

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace CoreWebSample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

若要變更WebRootPath的資料夾,可以修改Program.cs檔案,叫用UseWebRoot來指定,例如:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace CoreWebSample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseWebRoot("XXX")
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

沒有留言:

總瀏覽量