2017-05-16 39 views
8

için asp net çekirdek alternatif yolla mutlak yolunu almak ama o değil için Doğru sonuç ver.nasıl IHostingEnvironment</strong><strong>kullanmaya çalıştık</strong></p> <p><strong>Server.MapPath için asp net çekirdek alternatif yolla mutlak yolunu almak nasıl Server.MapPath

IHostingEnvironment env = new HostingEnvironment(); 
var str1 = env.ContentRootPath; // Null 
var str2 = env.WebRootPath; // Null, both doesn't give any result 

Ben bu mutlak yolunu almak gerekir wwwroot klasöründe bir resim dosyası (Sample.PNG) var. Bağımlı sınıfa bağımlı olarak Enjekte Et'i

+0

bağımlı sınıfa bir bağımlılık olarak enjekte konteyner ile hizmet kayıt emin olun. çerçeve sizin için doldurur. – Nkosi

cevap

18

. Eğer

public class HomeController : Controller { 
    private IHostingEnvironment _hostingEnvironment; 

    public HomeController(IHostingEnvironment environment) { 
     _hostingEnvironment = environment; 
    } 

    [HttpGet] 
    public IActionResult Get() { 
     var path = Path.Combine(_hostingEnvironment.WebRootPath, "Sample.PNG"); 
     return View(); 
    } 
} 

tek bir adım daha ileri gidip sana kendi yolunu sağlayıcı

public interface IPathProvider { 
    string MapPath(string path); 
} 

public class PathProvider : IPathProvider { 
    private IHostingEnvironment _hostingEnvironment; 

    public PathProvider(IHostingEnvironment environment) { 
     _hostingEnvironment = environment; 
    } 

    public string MapPath(string path) { 
     var filePath = Path.Combine(_hostingEnvironment.WebRootPath, path); 
     return filePath; 
    } 
} 

oluşturmak ve bağımlı sınıflara IPathProvider enjekte edebilir çerçevesi doldurmanız gerekir.

public class HomeController : Controller { 
    private IPathProvider pathProvider; 

    public HomeController(IPathProvider pathProvider) { 
     this.pathProvider = pathProvider; 
    } 

    [HttpGet] 
    public IActionResult Get() { 
     var path = pathProvider.MapPath("Sample.PNG"); 
     return View(); 
    } 
} 

services.AddSingleton<IPathProvider, PathProvider>(); 
+1

Genius! Sadece çalışma saatlerini kurtardın. – War10ck