Asp. net 코어 와 라 이브 러 리 에서 프로필 정 보 를 읽 습 니 다.

5187 단어 Asp.netcoremvc
건어물 을 보 려 면. net core 로 이동 하여 프로필 공공 류 를 읽 으 십시오.
먼저 뇌 동 을 열 었 습 니 다. Asp. net core 는 이렇게 오래 사용 되 었 습 니 다. 그러나 설정 파일 (json) 의 읽 기 에 대해 마이크로소프트 정 부 는. net framework 가 웹. config 를 읽 는 것 처럼 간단 하고 완벽 하지 않 은 것 같 습 니 다.마이크로소프트 가. net core 생태 번영 을 촉진 하기 위 한 작은 수단 이 라 고 심각하게 의심 하고 있다.
app setting. development. json (app setting. json 의 내용 과 차이 가 많 지 않 습 니 다. 다 중 환경 사용 에 대해 말씀 드 리 겠 습 니 다)
{
  "SettingPath": {
    "VideoFilePath": "C:\\Users\\89275\\Desktop\\Projects\\mv",
    "FfmpegPath": "C:/Users/89275/Desktop/Projects/mv/ffmpeg.exe",
    "FtpPath": "http://192.168.254.1/videofile",
    "VirtualPath": "/videoplay"
  },
  "RedisPath":"192.168.0.108:6379"
}


Asp. net core 에서 프로필 을 읽 는 블 로 그 를 많이 봤 는데 문제 가 잘 해결 되 지 않 은 것 같 습 니 다.
  • 가장 간단 한 것 은 StartUp 에서 Configuration ["SettingPath: VirtualPath"] 의 형식 으로 정 보 를 얻 는 것 이다.
  • 다음은 Controller 에서 설정 파일 정 보 를 얻 고 컨트롤 러 에서 설정 파일 을 읽 는 두 가지 방법 이 있 습 니 다.
  • 첫 번 째 는 controller 초기 화 할 때 IHosting Environment, IConfiguration 을 보 내 고 입 은 값 을 controller 에 해당 하 는 변수 에 부여 하 는 것 입 니 다. 술 을 마신 후에 설정 파일 을 정상적으로 읽 을 수 있 습 니 다.
         public class HomeController : Controller
        {
            //    
            private readonly IHostingEnvironment hostingEnvironment;
            private IConfiguration Configuration;
            public HomeController(IHostingEnvironment hostingEnvironment, IConfiguration configuration)
            {
                this.hostingEnvironment = hostingEnvironment;
                Configuration = configuration;
            }
    
            pubilc void GetRedisPath()
            {
                string redisPath = Configuration["RedisPath"];
            }
        }
    
  • 두 번 째 는 대상 을 가 져 오 는 방식 으로 프로필 을 읽 는 것 이다. 최근 많은 블 로그 들 이 이것 에 대해 말 하고 있다.아니면 controller 초기 화 할 때 IOptions 를 들 려 주 고 (여 기 는 내 가 어떻게 전 달 했 는 지 모 르 겠 어 / (12562, o, 12562) / ~) 전 달 된 값 을 Model 의 대상 에 게 부여 한 다음 에 정상적으로 사용 할 수 있 습 니 다.

  • 이 방법 은 StartUp 의 Configure Services 에 추가 해 야 합 니 다.
                services.AddOptions();
                //SettingPath  Model
                services.Configure(Configuration.GetSection("SettingPath"));
    
        public class HomeController
        {
    
            public SettingPath settingPath;
            private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(VideosController));
            public HomeController(IOptions option)
            {
                settingPath = option.Value;
            }
    
            public void GetVideoPath()
            {
                string path=SettingPath.VideoFilePath
            }
        }
    
    

    여기 서 IOptions 가 어떻게 들 어 왔 는 지 잘 모 르 기 때문에 두 개 이상 의 Model 만 사용 해 야 하 는 상황 이 있 으 면 어떻게 처리 해 야 할 지 모 르 겠 어 요.
    . net core 에서 프로필 공공 클래스 읽 기
    앞의 몇 가지 방법 은 이전에 모두 사용 한 적 이 있 지만, 개인 적 으로 는 쓰기 에 매우 편 하지 않다 고 느낀다.그리고 한 라 이브 러 리 에서 프로필 을 읽 으 려 면 며느리 를 상대 하고 싶 지 않 을 정도 로 고통스럽다.
    그래서 도구 류 를 직접 썼어 요.
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Options;
    using System;
    
    namespace Common
    {
        public class ConfigurationHelper
        {
            public IConfiguration config { get; set; }
            public ConfigurationHelper()
            {
                IHostingEnvironment env = MyServiceProvider.ServiceProvider.GetRequiredService();
                config = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();
            }
            public T GetAppSettings(string key) where T : class, new()
            {
                var appconfig = new ServiceCollection()
                    .AddOptions()
                    .Configure(config.GetSection(key))
                    .BuildServiceProvider()
                    .GetService>()
                    .Value;
                return appconfig;
            }
        }
        //           ,        
        public class MyServiceProvider
        {
            public static IServiceProvider ServiceProvider { get; set; }
        }
    }
    
    

    이 종 류 를 사용 하려 면 StartUp Configure 에 추가 해 야 합 니 다.
     MyServiceProvider.ServiceProvider = app.ApplicationServices;
    

    그 다음 에 설정 파일 정 보 를 어디서 든 읽 을 수 있 습 니 다. 또한 ConfigurationHelper 가 초기 화 되 었 을 때 환경 변 수 를 기본 으로 불 러 왔 기 때문에 다 중 환경 기능 도 갖 추고 있 습 니 다.
        string path = new ConfigurationHelper().config["RedisPath"];
                SettingPath pathss = new ConfigurationHelper().GetAppSettings("SettingPath");
    

    레 퍼 런 스
    https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/environments?view=aspnetcore-2.1 https://www.cnblogs.com/CreateMyself/p/6859076.html

    좋은 웹페이지 즐겨찾기