We have ASP.NET Core MVC project.Our Appsettings.json looks like below
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Connectionstring":"User ID= xdba; Password= sangram; Server= localhost; Port=5432; Database= sangram; Integrated Security=true; Pooling = true; "
},
"Application": {
"Name": "NhibernateMvc",
"MajorVersion": "1",
"MinorVersion": "8"
}
}
we will try to read Application part of AppSettings.json
Lets create a class that will mimic appsetting.json key Application.Say “AppSettings.cs”
namespace nhibernate_mvc.Settings
{
public class ApplicationSettings
{
public string Name { get; set; }
public string MajorVersion { get; set; }
public string MinorVersion { get; set; }
}
}
In Our Controller we need to modify Constructor to look like
private IConfiguration Configuration;
private readonly IOptions<ApplicationSettings> _AppSettings;
public BookController(IConfiguration _configuration,IOptions<ApplicationSettings> AppSetting)
{
Configuration = _configuration;
_repository = new Repository(_configuration.GetConnectionString("Connectionstring"));
_AppSettings = AppSetting;
}
we need to modify Startup.cs as follows
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//appsettings.json sections
services.Configure<ApplicationSettings>(Configuration.GetSection("Application"));
}
we can get “Application” values stored in appsettings.json as follows
[HttpPost]
public IActionResult Post([FromBody]Book Book)
{
if (Book.Id == 0)
{
Book.Name = _AppSettings.Value.Name;
Book.MajorVersion = _AppSettings.Value.MajorVersion;
Book.MinorVersion = _AppSettings.Value.MinorVersion;
Book newBook = _repository.AddBook(Book);
return new ObjectResult(newBook);
}
else
{
var existingOne = _repository.GetBook(Book.Id);
existingOne.Author = Book.Author;
existingOne.Title = Book.Title;
existingOne.Genre = Book.Genre;
existingOne.Name = _AppSettings.Value.Name;
existingOne.MajorVersion = _AppSettings.Value.MajorVersion;
existingOne.MinorVersion = _AppSettings.Value.MinorVersion;
_repository.UpdateBook(existingOne);
return new ObjectResult(existingOne);
}
}
Complete Code is available at
https://github.com/gitsangramdesai/nhibernate-aspnet-core
No comments:
Post a Comment