Skip to content

Add ASP.NET Core web app example #246

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 27, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Hocon.sln
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Hocon.API.Tests", "src\Hoco
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Hocon.Tests.Performance", "src\Hocon.Tests.Performance\Hocon.Tests.Performance.csproj", "{BD958665-7CE8-4DEF-89EA-8933393016D8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetWebApp", "src\examples\AspNetWebApp\AspNetWebApp.csproj", "{181D6251-3B11-4F2D-92E5-631C99D9F791}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -101,6 +103,10 @@ Global
{BD958665-7CE8-4DEF-89EA-8933393016D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BD958665-7CE8-4DEF-89EA-8933393016D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BD958665-7CE8-4DEF-89EA-8933393016D8}.Release|Any CPU.Build.0 = Release|Any CPU
{181D6251-3B11-4F2D-92E5-631C99D9F791}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{181D6251-3B11-4F2D-92E5-631C99D9F791}.Debug|Any CPU.Build.0 = Debug|Any CPU
{181D6251-3B11-4F2D-92E5-631C99D9F791}.Release|Any CPU.ActiveCfg = Release|Any CPU
{181D6251-3B11-4F2D-92E5-631C99D9F791}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -111,6 +117,7 @@ Global
{603AC356-4D9D-490C-BE69-685B792D2FD4} = {C3695FA9-B189-4881-864A-8377EE987B74}
{1437D06E-EA95-4599-A6D0-80C1EC774A5A} = {C3695FA9-B189-4881-864A-8377EE987B74}
{7A497666-0799-4165-88A4-1DB37DB65A8D} = {C3695FA9-B189-4881-864A-8377EE987B74}
{181D6251-3B11-4F2D-92E5-631C99D9F791} = {C3695FA9-B189-4881-864A-8377EE987B74}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {557DB117-9178-4935-B327-3017C53186FE}
Expand Down
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1113,3 +1113,18 @@ way to get rid of default fallback values they don't want.

Config keys are encouraged to be `hyphen-separated` rather than
`camelCase`.

# Hocon.Extensions.Configuration
`Hocon.Extensions.Configuration` is an extension of HOCON that
allows HOCON configuration files to be read and loaded into `Microsoft.Extensions.Configuration`

## Installation
To install [`Microsoft.Extensions.Configuration` via NuGet](https://www.nuget.org/packages/Hocon.Extensions.Configuration/):

```
PS> Install-Package Hocon.Extensions.Configuration
```

## Examples
An example project on how to use `Hocon.Extensions.Configuration` with ASP.NET Core
Web Application can be seen [in the examples folder](https://github.com/akkadotnet/HOCON/tree/dev/src/examples/AspNetWebApp)
30 changes: 30 additions & 0 deletions src/examples/AspNetWebApp/AspNetWebApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Content Include="appsettings.conf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="appsettings.Development.conf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DependentUpon>appsettings.conf</DependentUpon>
</Content>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Hocon.Extensions.Configuration" Version="2.0.1" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Abstractions" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="3.1.2" />
</ItemGroup>

</Project>
43 changes: 43 additions & 0 deletions src/examples/AspNetWebApp/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetWebApp.Models;

namespace AspNetWebApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}

public IActionResult About()
{
ViewData["Message"] = "Your application description page.";

return View();
}

public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";

return View();
}

public IActionResult Privacy()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
11 changes: 11 additions & 0 deletions src/examples/AspNetWebApp/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace AspNetWebApp.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
51 changes: 51 additions & 0 deletions src/examples/AspNetWebApp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Hocon.Extensions.Configuration;

namespace AspNetWebApp
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureAppConfiguration((hostingContext, config) =>
{
// We inject the HOCON configuration file using this function call,
// the rest of the code are there to make sure that the final configuration
// conforms to the Microsoft standard on loading a full configuration stack.
var env = hostingContext.HostingEnvironment;
config.AddHoconFile("appsettings.conf", optional: false, reloadOnChange: true)
.AddHoconFile($"appsettings.{env.EnvironmentName}.conf", optional: true, reloadOnChange: true);

if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}

config.AddEnvironmentVariables();

if (args != null)
{
config.AddCommandLine(args);
}
});
}
}
27 changes: 27 additions & 0 deletions src/examples/AspNetWebApp/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51951",
"sslPort": 44305
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"AspNetWebApp": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
48 changes: 48 additions & 0 deletions src/examples/AspNetWebApp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Hocon.Extension.Configuration Web Application Sample

This is an example on how to use `Hocon.Extension.Configuration` nuget package with an ASP.NET Core 3.1 Web Application project.
The project file was made in Visual Studio 2019.

The code needed to inject the HOCON configuration file into the Web Application configuration singleton instance
is located inside the `Program.cs` file.

```C#
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
// We inject the HOCON configuration file using this function call,
// the rest of the code are there to make sure that the final configuration
// conforms to the Microsoft standard on loading a full configuration stack.
var env = hostingContext.HostingEnvironment;
config.AddHoconFile(
"appsettings.conf",
optional: false,
reloadOnChange: true)
.AddHoconFile(
$"appsettings.{env.EnvironmentName}.conf",
optional: true,
reloadOnChange: true);

if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}

config.AddEnvironmentVariables();

if (args != null)
{
config.AddCommandLine(args);
}
});
}
```
63 changes: 63 additions & 0 deletions src/examples/AspNetWebApp/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AspNetWebApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});


services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
7 changes: 7 additions & 0 deletions src/examples/AspNetWebApp/Views/Home/About.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@{
ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>
17 changes: 17 additions & 0 deletions src/examples/AspNetWebApp/Views/Home/Contact.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
@{
ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>

<address>
<strong>Support:</strong> <a href="mailto:[email protected]">[email protected]</a><br />
<strong>Marketing:</strong> <a href="mailto:[email protected]">[email protected]</a>
</address>
Loading