I'm on a new ASP.NET 5 project.
I'm trying to read an array value, stored in my config.json file, that looks like this:
{
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": ["www", "info", "admin"]
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-MyProject....."
}
}
}
How do I access this from my C# code?
At least with beta4 arrays aren't supported in config.json. See ASP.NET issue 620. But you could use the following config.json:
"AppSettings": {
"SiteTitle": "MyProject",
"Tenants": {
"ReservedSubdomains": "www, info, admin"
}
}
and map it to a class like this:
public class AppSettings
{
public string SiteTitle { get; set; }
public AppSettingsTenants Tenants { get; set; } = new AppSettingsTenants();
}
public class AppSettingsTenants
{
public string ReservedSubdomains { get; set; }
public List<string> ReservedSubdomainList
{
get { return !string.IsNullOrEmpty(ReservedSubdomains) ? ReservedSubdomains.Split(',').ToList() : new List<string>(); }
}
}
This can then be injected into a controller:
public class MyController : Controller
{
private readonly AppSettings _appSettings;
public MyController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Options;
}
Related
I am trying to do a get all with an ASP.NET Core project that uses this firebase library and I can't seem to return the children nested in an object. I have 3 classes: Route, Via & Waypoints(Serves as a bridge for JSON Deserialization).
public class Route
{
public string Route_ID { get; set; }
public string Destination { get; set; }
public string Origin { get; set; }
public Waypoints Stops { get; set; }
public Route()
{
}
}
public class Via
{
public string Via_ID { get; set; }
public string Route_ID { get; set; }
public int Seq_Number { get; set; }
public string Coordonnees { get; set; }
public string Description { get; set; }
public Via()
{
}
}
public class Waypoints
{
public List<Via> Vias;
public Waypoints()
{
}
}
In my GET method I go Fetch everything from my Routes and want to return it as one JSON List containing all my routes along with their waypoints but it only returns an empty list of Waypoints:
[HttpGet]
public async Task<IEnumerable<Route>> Get()
{
List<Route> routes = (await firebaseClient
.Child("routes")
.OrderByKey()
.OnceAsync<Route>())
.Select(item =>
new Route
{
Route_ID = item.Key,
Origin = item.Object.Origin,
Destination = item.Object.Destination,
Waypoints = item.Object.Waypoints
}).ToList();
foreach (Route route in routes)
{
List<Via> vias = (await firebaseClient
.Child("routes")
.Child(route.Route_ID)
.Child("Waypoints")
.OrderByKey()
.OnceAsync<Via>())
.Select(waypoint =>
new Via
{
Via_ID = waypoint.Key,
Route_ID = waypoint.Object.Route_ID,
Coordonnees = waypoint.Object.Coordonnees,
Seq_Number = waypoint.Object.Seq_Number,
Description = waypoint.Object.Description
}).ToList();
if(vias.Count > 0)
{
route.Stops.Vias = vias;
}
}
return routes;
}
My data structure:
{
"routes" : {
"987321": {
"Destination": "13.13;-12.34",
"Origin": "12.12;-12.12",
"Route_ID": "987321",
"Waypoints": {
"4d5e6f": {
"coordonnees": "45.8;-74.7",
"description": "Description",
"route_id": "987321",
"seq_number": 2,
"via_id": "4d5e6f"
},
"111222": {
"coordonnees": "45.8;-74.7",
"description": "Description",
"route_id": "987321",
"seq_number": 1,
"via_id": "111222"
}
}
}
}
}
And finally my call result:
[
{
"route_ID": "987321",
"destination": "13.13;-12.34",
"origin": "12.12;-12.12",
"waypoints": {}
}
]
It seems the Deserializing doesn't go further than the first layer of children. Is there any solution to this?
Thanks to Rena's suggestion, I figured out that the problem was located in my Waypoints bridging class that was missing a { get; set; }
Here is the change that was made to my class:
public class Waypoints
{
public List<Via> Vias { get; set; }
public Waypoints()
{
}
}
I've already searched, there are similar questions, but with JSON Array in answers they are using IConfigure in the controller. I can use IConfigure only in Startup.
I have this JSON Array in appsettings.json
{
"EmailList":[
{
"name":"John Algovich",
"email":"John.Algovich#mail.com"
},
{
"name":"Petr Algr",
"email":"Petr.Algr#mail.com"
},
{
"name":"Mathew Cena",
"email":"Mathew.Cena#mail.com"
}
]
}
EmailList.cs:
public class EmailAddress {
public string Name { get; set; }
public string Email { get; set; }
}
public class EmailList {
public List<EmailAddress> EmailArray { get; set; }
}
There is a lot of injections in Startup.cs, so I used the same code for mine:
services.Configure<EmailList>(Configuration.GetSection("EmailList"));
Controller:
public class DevController : Controller
{
private readonly EmailList _devEmailList;
private List<string> _emailList;
public DevController(
IOptions<EmailList> _devEmailList,
{
_devEmailList = devEmailList.Value;
_emailList = new List<string>();
}
}
public IActionResult Index()
{
var result = _devEmailList; // Returns null
var mailData2 = JsonConvert.DeserializeObject<EmailList>(_devEmailList.EmailArray.ToString()); // Returns null
}
Goal: How can get email adresses in Controller using Options and add it to the list?
Ok, so I was able to solve the problem:
I kept my appsettings.json the way it is with config classes.
I changed Startup code to this:
EmailInfo[] emails = Configuration.GetSection("EmailList").Get<EmailInfo[]>();
services.Configure<EmailList>(options => {options.EmailArray = emails.ToList();});
In my Controller:
This stays the same
public class DevController : Controller
{
private readonly EmailList _devEmailList;
private List<string> _emailList;
public DevController(
IOptions<EmailList> _devEmailList,
{
_devEmailList = devEmailList.Value;
_emailList = new List<string>();
}
}
Getting emails:
public IActionResult Index() {
var result = _udeEmailList.EmailArray;
foreach (var mailInfo in result)
{
emailsList.Add(mailInfo.Email);
}
}
what you are retrieving as your section is IEnumerable<EmailAddress> not EmailList. Read what you wrote, in your config there's no "EmailArray" definition.
You can add another level in your config (useful if you will have more things relative to email configuration in that section) or change the type to IEnumerable<EmailAddress> (not needed to be concretely IEnumerable, anything that implements it like an array or a list will work).
If you go for the first option you must do something like this:
In your config file...
{
"EmailConfig":{
"EmailList":[
{
"name":"John Algovich",
"email":"John.Algovich#mail.com"
},
{
"name":"Petr Algr",
"email":"Petr.Algr#mail.com"
},
{
"name":"Mathew Cena",
"email":"Mathew.Cena#mail.com"
}
]
//You can add here more properties
}
}
Your config classes:
public class EmailAddress
{
public string Name { get; set; }
public string Email { get; set; }
}
public class EmailConfig
{
public List<EmailAddress> EmailList { get; set; }
}
Your configuration:
services.Configure<EmailConfig>(Configuration.GetSection("EmailConfig"));
And the controller:
public class DevController : Controller
{
private readonly EmailConfig _mailConfig;
public DevController(IOptions<EmailConfig> mailConfig)
{
_mailConfig = mailConfig.Value;
}
public IActionResult Index()
{
var result = _mailConfig.EmailList;
}
}
I'm trying to read in a local JSON file that contains various objects. But the object always returns null.
I know that the Resources.Load<TextAsset>(_directory + _fileName).text; has successfully found the file, since I can output the text to the console.
My goal is to be able to ask for a key and get back the value for the selected language. ie: hello_world.sp would return Hola, mundo.
However, anytime I go to access any object like Debug.Log(lang.languageList.Count); I get the error:
NullReferenceException: Object reference not set to an instance of an
object
Eventually, I would like to be able to add additional language values, fr,it, etc...
Can anyone see what I am doing wrong?
lang.json
{
"hello_world": {
"en": "Hello, World!",
"sp": "Hola, mundo"
},
"button_ok": {
"en": "Yes",
"sp": "Si"
},
"button_cancel": {
"en": "Cancel",
"sp": "Cancelar"
}
}
JSONLoad.cs
public class JSONLoader
{
private static readonly string _directory = "Langs/";
private static readonly string _fileName = "lang";
private string ReadJsonFile() { return Resources.Load<TextAsset>(_directory + _fileName).text; }
public void Load()
{
var file = ReadJsonFile();
var lang = JsonUtility.FromJson<LanguageObject>(file);
Debug.Log(lang);
}
}
[Serializable]
public class LangValue
{
public string en { get; set; }
public string sp { get; set; }
}
[Serializable]
public class LangKey
{
public string id { get; set; }
public List<LangValue> children { get; set; }
}
[Serializable]
public class LanguageObject
{
public List<LangKey> languageList { set; get; }
}
Your Json structure doesn't match your classes. It's not a list. Here's a working example:
Json:
{
"languageList":
[
{
"id": "hello_world",
"children": {
"en": "Hello, World!",
"sp": "Hola, mundo"
}
},
{
"id": "button_ok",
"children": {
"en": "Yes",
"sp": "Si"
}
},
{
"id": "button_cancel",
"children": {
"en": "Cancel",
"sp": "Cancelar"
}
}
]
}
Classes:
[Serializable]
public class LangValue
{
public string en;
public string sp;
}
[Serializable]
public class LangKey
{
public string id;
public LangValue children;
}
[Serializable]
public class LanguageObject
{
public List<LangKey> languageList;
}
PS: I'm not a fan of JsonUtility I'd rather go for Json.Net which allows the use of properties among other things.
According to the docs, JSON serialization using UnityEngine.JsonUtility relies on models having public fields, not properties. You'll need to define your models with fields instead of properties.
Ie.,
[Serializable]
public class LangValue
{
public string en;
public string sp;
}
[Serializable]
public class LangKey
{
public string id;
public List<LangValue> children;
}
[Serializable]
public class LanguageObject
{
public List<LangKey> languageList;
}
I am trying to create a gateway api using net core. When I try to redirect the call using app.route :
app.Run(async (context) =>
{
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var routing = serviceScope.ServiceProvider.GetService<IRoutingService>();
var content = await routing.RouteRequest(context.Request);
await context.Response.WriteAsync(await content.Content.ReadAsStringAsync());
content.Dispose();
// Seed the database.
}
});
... And RoutingService service starts like :
public class RoutingService : IRoutingService
{
private readonly RouteManagement _routeManagement;
static HttpClient _client = new HttpClient();
public RoutingService(IOptions<RouteManagement> routeManagement)
{
_routeManagement = routeManagement.Value;
}
...
.. I can not get the values from json file filled. The following is the json file :
{
"tokenManagement": {
"secret": "Any String used to sign and verify JWT Tokens, Replace this string with your own Secret",
"issuer": "threenine.co.uk",
"audience": "SampleAudience",
"accessExpiration": 30,
"refreshExpiration": 60
},
"routeManagement": {
"Routes": [
{
"Endpoint": "/coupons",
"Destination": {
"Uri": "http://localhost:30561/coupons/",
"RequiresAuthentication": "true"
}
},
{
"Endpoint": "/songs",
"Destination": {
"Uri": "http://localhost:8091/songs/",
"RequiresAuthentication": "false"
}
}
]
}
}
Am I doing smth wrong? The following is the class RouteManagement
public class RouteManagement
{
public List<Routes> Routes { get; set; }
}
public class Routes
{
public string Endpoint { get; set; }
public Routes.DestinationManagement Destination { get; set; }
public class DestinationManagement
{
private DestinationManagement()
{
Uri = "/";
RequiresAuthentication = false;
}
public string Uri { get; set; }
public bool RequiresAuthentication { get; set; }
}
}
Follow steps below to resolve your issue:
Register RouteManagement
services.Configure<RouteManagement>(Configuration.GetSection("routeManagement"));
You need to make DestinationManagement() public, otherwise, it will fail to initialize the DestinationManagement
public class RouteManagement
{
public List<Routes> Routes { get; set; }
}
public class Routes
{
public string Endpoint { get; set; }
public Routes.DestinationManagement Destination { get; set; }
public class DestinationManagement
{
public DestinationManagement()
{
Uri = "/";
RequiresAuthentication = false;
}
public string Uri { get; set; }
public bool RequiresAuthentication { get; set; }
}
}
Have you registered the configuration instance which RouteManagement binds against in ConfigureServices method ?
services.Configure<RouteManagement>(Configuration);
Entity framework/MVC newbie here.
Writing my first EF application (api). So far so good, I can retrieve rows from the database but now I'm blocked by a problem which I can't wrap my head around.
I can't figure out how to manipulate the values returned. I retrieve a resultset with 5 columns and I want to encrypt the individual values before returning it to the calling app in a JSON string. Can anyone point me to an example on where in the code to achieve this? Model? Repository? I'm lost here.
namespace app.Models
{
public class ParameterSet
{
public int id { get; set; }
public string DbServerInstance { get; set; }
public string DbServerUser { get; set; }
public string DbServerPassword { get; set; }
public string DbServerDatabase { get; set; }
}
}
Connection context
namespace app.Repositories
{
public class DbconnectionContext : DbContext
{
public DbconnectionContext() : base("MobileAppsConnection")
{
Database.SetInitializer<DbconnectionContext>(null);
}
public DbSet<ParameterSet> ParameterSet { get; set; }
}
}
interface
namespace app.Repositories
{
interface IParameterSets
{
IEnumerable<ParameterSet> ListofParameterSet();
}
}
repository
namespace MobileAppsService.Repositories
{
public class ParameterSets : IParameterSets
{
public IEnumerable<ParameterSet> ListofParameterSet()
{
using (DbconnectionContext context = new DbconnectionContext())
{
var listofparameters = from parameters in context.ParameterSet
select parameters;
return listofparameters.ToList();
}
}
}
}
values controller
namespace MobileAppsService.Controllers
{
public class ValuesController : ApiController
{
readonly IParameterSets Iparamset;
public ValuesController()
{
Iparamset = new ParameterSets();
}
// GET api/values
public IEnumerable<ParameterSet> GetAlldata()
{
return Iparamset.ListofParameterSet();
}
}
}
You should manipulate the result set in the controller before returning it to the client. you don't have to make this data manipulation in the data layer.
namespace MobileAppsService.Controllers
{
public class ValuesController : ApiController
{
readonly IParameterSets Iparamset;
public ValuesController()
{
Iparamset = new ParameterSets();
}
// GET api/values
public IEnumerable<ParameterSet> GetAlldata()
{
var paramList = Iparamset.ListofParameterSet();
//do encryption of the paramlist here
//return the encrypted paramlist
return paramList;
}
}
}