I am having an issue while trying the WebAPI of net core.
For some reason my object always comes empty no matter what I try. I've checked several other SO questions regarding this but cannot find a solution for what I am facing.
My model:
My controller (getting the null object):
And the POSTMAN request:
I've tried both with and without the [FromBody] option as I've seen in other SO questions that some people solved their issues with it.
Any ideas?
All the auto-implemented properties must have an public modifier before them to for JSON.NET to safely deserialize them.
public class APIRequest
{
string Action { get; set; }
}
Because in the above example no access modifier is given, thereby making it as private, so the default value of the property is assigned which is default(string) that is null.
public class APIRequest
{
public string Action { get; set; }
}
By default all class members are private and the class itself is internal, so you have to mark your property with public modifier.
Related
I looked for this question, and altough there are similar questions asked, I could not find an answer.
So I have a problem. I have 2 classes:
public class Person {
public string name{ get; set; }
}
public class Doctor: Person{
public string specialization{ get; set; }
}
And I have controller:
[HttpPost]
...
public virtual IActionResult PostPerson([FromBody]Person person)
{ ... }
How can I make it so that if I send JSON like this:
{"specialization":"obgyn"}
that I get Doctor object in my controller?
Do I need to make custom binding (is there an example? however I have much much more classes like this (100ts) so I would not like to do it for each class specifically) or set JsonOptions in Startup.cs, or something third??
Thank you.
So the way to get this working is t oadd in your Startup.cs file a JSonOptions:
opts.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All;
This would then add $type properties to response, and would also read $type from incoming Json Messages. Unfortunatly, my clients wish changed because he does not want to identify the class by that field, but a custom another one, so this solution is not for me, but the answer my still help someone
Is it possible to make the ServiceStack.Text library throw when attempting to deserialize invalid JSON. By default it looks as if invalid JSON is just ignored, so that the result object contains null values.
When I attempt to deserialize this json (a " is missing after MongoConnectionString)
{
"MongoDb": {
"MongoConnectionString:"mongodb://localhost:27017/x",
"MongoDatabase":"x",
"MongoSafeModeEnabled":true,
"MongoSafeModeFSync":true,
"MongoSafeModeWriteReplicationCount":
"MongoSafeModeWriteTimeout":"00:00:00"
},
by doing this: JsonSerializer.DeserializeFromString(json);
where
public class Configuration {
public class MongoDbSettings
{
public string MongoConnectionString {get;set;}
public string MongoDatabase {get;set;}
public bool MongoSafeModeEnabled {get;set;}
public bool MongoSafeModeFSync {get;set;}
public int MongoSafeModeWriteReplicationCount {get;set;}
public TimeSpan MongoSafeModeWriteTimeout {get;set;}
}
}
I get a Configuration object where MongoDbSettings is null. I would prefer to get an exeception in this case. Is this possible?
At the moment the ServiceStack serializers are optimized for resilience, i.e. deserialize as much as possible without error.
I'd recommend adding some of your own validation checking post serialization to work out which fields weren't deserialized correctly.
You could also submit a pull-request to the ServiceStack.Text project that supports an opt-in flag (i.e. on JsConfig) to change the behavior to throw exceptions.
Another 'Entity Type 'x' has no key defined' question, but I've set the [Key] attribute on a property so I'm a bit confused.
Here's my entity and context classes:
namespace DoctorDB.Models
{
public class Doctor
{
[Key]
public string GMCNumber;
[Required]
public string givenName;
[Required]
public string familyName;
public string MDUNumber;
public DateTime MDUExpiry;
public string MDUCover;
}
public class DoctorContext : DbContext
{
public DbSet<Doctor> Doctors { get; set; }
}
}
When I go to create my controller, I've selected to create it with the Entity Framework methods using this entity and context:
and I get this error:
My only thought is whether you can't successfully use [Key] on a string property. If you can't then fair enough, I'll work round it, but I'd be grateful if someone could confirm this one way or the other.
You need to change GMCNumber to a property not a field.
To help clarify, this line:
public string GMCNumber;
needs to become:
public string GMCNumber { get; set; }
I encountered the same error message when I had defined the property as private.
I ran into this post after facing a similar issue today. The problem was that I was attempting to create the scaffold after adding the [Key] attribute to my model and without compiling. Once I compiled with the [Key] attribute the scaffolding generated just fine.
Using Windsor 2.5.2, the following works:
public class Foo
{
public IBar Bar { get; set; }
}
To delay creation of IBar, this also works:
public class Foo
{
public Foo(Func<IBar> barFactory)
{
}
}
However, if I combine property injection with Func<T>, the following results in a null reference:
public class Foo
{
public Func<IBar> Bar { get; set; }
}
How can I make Windsor inject the Func<IBar>?
That's a great question Paul. I'm glad you asked.
For implicitly registered Funcs Windsor is looking at the property, sees it's optional, and it just doesn't bother trying to get it, since... well - it's optional, so you surely are happy not having the dependency populated.
To have it populated, you either register the factory explicitly
container.Register(Component.For<Func<IBar>>().AsFactory().Lifestyle.Transient);
or you mark the dependency as required (on ComponentModel using Require method) which is probably best done via an IComponentModelConstructionContributor
I have carried the method here on almost all of the areas where I have had overridable methods and managed to fix them but there is one part where the method doesnt work in the same way on a different contexted piece of code:
public Employee()
{
this.InitMembers();
}
private void InitMembers()
{
// Init the collection so it's never null
this.Territories = new List<Territory>();
}
public Employee(string firstName, string lastName): this()
{
this.reffirstName = firstName;
this.reflastName = lastName;
}
> public virtual IList<Territory> Territories { get; protected set; }
Where again the > is the code causing the error, I do however get an intellisense option to "Convert to auto property", which simply reverts the code to when it was started and not fixing the problem.
Anyone know what modifications need to be made to this part to elimiate the fxcop violation?
The error appears because your private constructor is calling a method that can be overridden from a derived class. To fix the warning, you need to remove any calls to virtual methods from within the constructor.
In the example you list, InitMembers uses 'this.Territories', which is causing the violation. According to your later comment you have added a private member - use that instead.