Using an appsetting.json variable inside a model - asp.net

I'm using .Net and i need to use inside a virtual field of a model a variable defined inside appsettings.json. Something like:
public class MyClass : BaseClass {
[NotMapped]
public virtual string? identifier { get{
return $"{PlantAcronym} {otherstuff}";
}
}
}
appsetting.json looks like this:
{
"Logging": {
...
},
"AllowedHosts": "*",
"Settings":{
"PlantAcronym": "Z",
...,
"SQLConnectionString": "...",
...
}
}
basically, i need to get the variable without using a constructor.
I've tried approaches using static classes like the most answered question here but they return null and i don't know why.
My setup look like this:
service.Configure<Settings>(options =>
{
options.z = _configuration.GetSection("Settings").GetSection("PlantAcronym").Value;
});
public class Settings{
public string z { get; set; }
public static string PlantAcronym { get; set;}
public Settings(string configuration){
z = configuration;
PlantAcronym = z;
}
public static string getPlantAcronym(){
return PlantAcronym;
}
}

Related

How to get API response key values in PascalCase as same as the object variable name in .net core 3.1 only for one controller or one function?

This is my Object Class
public class MyObject
{
Public string Var1 { get; set; }
Public string Var2 { get; set; }
}
This is a get function of my controller class
[HttpGet]
public IActionResult GetObjList()
{
return Ok(new GenericModel<List<MyObject>>
{
Data = myobjectList
});
}
The GenericModel contains
public class GenericModel<T>
{
public T Data { get; set; }
public string[] Errors { get; set; }
}
My expected result look like this
{
"Data": [
{
"Var1": "val1",
"Var2": "val2"
}
]
}
But I'm getting this,
{
"data": [
{
"var1": "val1",
"var2": "val2"
}
]
}
I just want to get the output key values as same as the object variables, (in PascalCase)
I tried the solutions to add "AddJsonOptions" into the Startup.cs but they did not work. And I want the response as Pascal case, only for this controller requests, not in all requests including other controllers. (Sounds odd, but I want to try it) Are there any solutions? Is is impossible?
There may be another solution but I suggest building ContentResult yourself with JsonSerializer:
[HttpGet]
public IActionResult GetObjList()
{
return this.Content(JsonSerializer.Serialize(yourResult, yourJsonOption), "application/json");
}
For Pascal Case serialization use this code in Startup.cs:
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy= null;
);

How to parse attribute in JsonConvert.DeserializeObject

We have following JSON output from an API.
We are using the following code in ASP.NET to deserialize a JSON response to a class:
var j = JsonConvert.DeserializeObject<classname>(response);
While deserializing the following JSON, we are unable to get the attribute values.
{
"User": {
"Address": {
"#CityName": "Test",
"$": "B4C99EB0-18E6-439F-882A-9E4A11E1FF75"
}
}
}
As per the above example we need to get #cityname and $ attribute values.
We need following output in the class:
#CityName : Test
$ : B4C99EB0-18E6-439F-882A-9E4A11E1FF75
I am getting the element value, but I am not able to get the attribute values.
Is there a way I can do this?
You can use the [JsonProperty] attribute to map non-standard JSON property names to properties in your class. Make your classes like this:
public class RootObject
{
public User User { get; set; }
}
public class User
{
public Address Address { get; set; }
}
public class Address
{
[JsonProperty("#CityName")]
public string CityName { get; set; }
[JsonProperty("$")]
public string Guid { get; set; }
}
Then deserialize like this:
var obj = JsonConvert.DeserializeObject<RootObject>(response);

Writing CDATA in ASP.NET WebApi

Im using the setting:
formatters.XmlFormatter.UseXmlSerializer = true;
The class i try to serailize is quite simple:
public class MyClass
{
public MyClass()
{
CDATA = "<![CDATA[<link>MyLink</link>]]>"
[XmlText]
public string CDATA { get; set; }
}
I want this to be serialized into something like:
<MyClass>
<![CDATA[<link>MyLink</link>]]>
</MyClass>
But instead get:
<MyClass>
<![CDATA[<!link>MyLink<!/link>]]>
</MyClass>
So how can i prevent this? Or is there a better way using the ASP.NET WebApi?
Looks like the answer from this question will do it:
[XmlIgnore] public string Content { get; set; }
[XmlText]
public XmlNode[] CDataContent {
get {
return new XmlNode[] {
new XmlDocument().CreateCDataSection(Content)
};
}
set { Content = value[0].Value; }
}
This works with a regular XmlSerializer object, so I'd guess it works in WebAPI as well.

DataContract Name Attribute not Working with Json Serializer

I'm building a JSON only WepApi and I have a controller which returns a list.
I have decorated the list with Datacontract/Datamember attributes like this:
[DataContract(Name = "Files", Namespace = "http://schemas.example.com")]
public class FileDesc
{
[DataMember(Name = "MyFileName")]
public string Name { get; set; }
[DataMember(Name = "MyFilePath")]
public string Path { get; set; }
[DataMember(Name = "MyFileSize")]
public long? Size { get; set; }
public FileDesc(string n, string p, long? s)
{
Name = n;
Path = p;
Size = s;
}
}
In my controller I return the list like this:
// Response
List<FileDesc> FileList = new List<FileDesc>();
foreach (MultipartFileData file in provider.FileData)
{
FileList.Add(new FileDesc(file.Headers.ContentDisposition.FileName, file.LocalFileName , file.Headers.ContentDisposition.Size ));
}
return FileList;
But in the JSON output the Name attribute for the list is missing:
[
{
"myFileName": "\"ArduinoUNO.png\"",
"myFilePath": "c:\\images\\ArduinoUNO.png",
"myFileSize": null
}
]
To force JSON-only output i have removed the xml formatter on Global.asax:
//Only JSON
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
Thanks in advance
Arrays don't have names by themselves in JSON. If you want a name on the list, you need an outer object that has a named property to hold the list.
Something like this:
public class Response
{
[DataMember(Name = "Files")]
List<FileDesc> FileList { get; set; }
}
The JSON would then look like this:
{
"Files":
[
{
"myFileName": "\"ArduinoUNO.png\"",
"myFilePath": "c:\\images\\ArduinoUNO.png",
"myFileSize": null
}
]
}

Why are public properties being serialized w/ an underscore in MVC4?

In the following class
using System;
namespace Beverati.Repository.ViewModel
{
[Serializable]
public class CollectionItem : EditableEntityBase
{
public CollectionItem() {}
private int? _quantity;
private string _retailValue;
private string _currencyName;
public int? quantity
{
get { return this._quantity ?? NULL_INTEGER; }
set { this._quantity = value; }
}
public string retailValue
{
get { return this._retailValue ?? String.Empty; }
set { this._retailValue = value; }
}
public string currencyName
{
get { return this._currencyName ?? String.Empty; }
set { this._currencyName = value; }
}
}
}
returned in this controller action
public IEnumerable<Repository.ViewModel.CollectionItem> GetAll()
produces this JSON output with MVC2 the JSON output like this
{
quantity:2
retailValue: 50.00
currencyName: USD
}
However, when I installed MVC4 the JSON returned looks like this
{
_quantity:2
_retailValue: 50.00
_currencyName: USD
}
All the property names have an underscore prefix. Why is the underscore being used and what should be done to have the public property names returned in the JSON?
The [Serializable] attribute is what's doing it - Assuming you don't need it for another purpose - remove the attribute and all should be well.

Resources