如何为Angular 2和ASP.NET Core MVC共享环境变量 [英] How to have a shared environment variable for Angular 2 and ASP.NET Core MVC

查看:171
本文介绍了如何为Angular 2和ASP.NET Core MVC共享环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET Core MVC项目中有一个Angular 2应用程序. Angular 2应用程序和Startup.cs都将具有用于特定环境的代码,即.使用http://localhost作为Web服务url而不是http://devserver(发布时应使用).我需要以编程方式执行此操作,因此我宁愿在未在操作系统中设置ASPNETCORE_ENVIRONMENT的情况下也不执行此操作.有没有办法做到这一点?

I have an Angular 2 application in an ASP.NET Core MVC project. Both Angular 2 application and Startup.cs will have code for specific environments, ie. use http://localhost as web service url instead of http://devserver(should be used when published). I need to do this programmatically so I rather do not do this without setting ASPNETCORE_ENVIRONMENT in the OS. Is there a way to accomplish this?

推荐答案

我已经做到了.不确定这是否是最佳解决方案,但对我有用.

I've managed to do this. Not sure if it's an optimal solution but it works for me.

请注意,最后,我选择了基于配置的文件(即,如果在Debug配置中,则使用.Debug.file)作为解决方案,而不是基于环境变量的配置.

创建appsettings.json.当您按F5键以调试模式运行项目时,将读取此内容.还要设置appsettings.json"Copy to Output directory: Copy if newer":

Create appsettings.json. This will be read when you press F5 to run the project in debug mode. Also set appsettings.json "Copy to Output directory: Copy if newer":

{
  "AppSettings": {
    "MyApiUrl": "http://localhost:23224/v1/"
  }
}

创建appsettings.Debug.json.当您发布项目时(假设您正在使用Debug配置进行发布),将使用此方法:

Create appsettings.Debug.json. This will be used when you publish the project (assuming you are using Debug configuration for publish):

{
  "AppSettings": {
    "MyApiUrl": "http://api.server.com/v1/"
  }
}

编辑您的.csproj以添加AfterBuild事件,以便在构建时将appsettings.json文件复制到/wwwroot(假定Angular 2应用程序位于wwwroot文件夹中),以便Angular可以读取它:

Edit your .csproj to add AfterBuild event to copy appsettings.json file to /wwwroot when you build (assuming your Angular 2 application is in wwwroot folder) so Angular can read it:

<Target Name="AfterBuildOperations" AfterTargets="AfterBuild">
    <Copy SourceFiles="$(ProjectDir)appsettings.json" DestinationFiles="$(ProjectDir)wwwroot\appsettings.json" OverwriteReadOnlyFiles="true" />
  </Target>

编辑.csproj,将appsettings.Debug.json重命名为appsettings.json,并在发布时将其复制到wwwroot文件夹.由于某些原因,VS.NET publish在发布输出文件夹中同时包含appsettings.json和appsettings.Debug.json:

Edit your .csproj to rename appsettings.Debug.json to appsettings.json and copy it to wwwroot folder when you publish it. For some reason VS.NET publish includes both appsettings.json and appsettings.Debug.json in the publish output folder:

<Target Name="AfterPublishOperations" AfterTargets="AfterPublish">
    <Delete Files="$(ProjectDir)bin\$(ConfigurationName)\PublishOutput\appsettings.json" />
    <Copy SourceFiles="$(ProjectDir)bin\$(ConfigurationName)\PublishOutput\appsettings.$(ConfigurationName).json" DestinationFiles="$(ProjectDir)bin\$(ConfigurationName)\PublishOutput\appsettings.json" />
    <Delete Files="$(ProjectDir)bin\$(ConfigurationName)\PublishOutput\appsettings.$(ConfigurationName).json" />
    <Copy SourceFiles="$(ProjectDir)bin\$(ConfigurationName)\PublishOutput\appsettings.json" DestinationFiles="$(ProjectDir)bin\$(ConfigurationName)\PublishOutput\wwwroot\appsettings.json" OverwriteReadOnlyFiles="true" />
  </Target> 

AppSettings.cs模型添加到您的项目中以获得强类型的配置:

Add AppSettings.cs model to your project to get configuration strongly-typed:

public class AppSettings
    {
        public string MyApiUrl { get; set; }
    }

读取Startup.cs中的appsettings.json内容并将其作为单例添加到DI容器:

Read appsettings.json contents in Startup.cs and add it as a singleton to DI container:

public void ConfigureServices(IServiceCollection services)
        {
            var appSettings = ReadConfiguration();
            services.AddSingleton(appSettings);
        }

        public AppSettings ReadConfiguration()
        {
            var section = Configuration.GetSection("AppSettings");
            var settings = new AppSettings();
            new ConfigureFromConfigurationOptions<AppSettings>(section).Configure(settings);

            return settings;
        }

您可以将AppSettings注入到您的控制器中:

You can inject AppSettings to your controllers:

private AppSettings appSettings;

public MyController(AppSettings appSettings)
{
    this.appSettings = appSettings;
}

AppSettings.ts添加到Angular 2中

Add AppSettings.ts to your Angular 2

export interface AppSettings {
    MyApiUrl?: string;
}

现在您可以在Angular 2中的任何位置阅读它.

Now you can read it anywhere you want in Angular 2:

private ReadAppSettings() {
        this.http.get('/appsettings.json')
            .map(response => response.json())
            .subscribe(result => {
                let appSettings: AppSettings = <AppSettings>result.AppSettings;
            },
            error => { console.error(error); });
    }

这篇关于如何为Angular 2和ASP.NET Core MVC共享环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆