My model is
using Newtonsoft.Json;
...
public class User
{
public int Id { get; set; }
public string Login { get; set; }
public string Password { get; set; }
[JsonIgnore]
public string Email { get; set; }
public User()
{
}
}
and controller method is
[HttpPost]
public async Task<ActionResult<User>> PostUser(User user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return CreatedAtAction("GetUser", new { id = user.Id }, user);
}
I am using adding newtonsoft to a project in Program.cs like that:
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
And when i try to post user in postman, i getting validation error neither i am including email field or not:
"errors": {
"Email": [
"The Email field is required."
]
},
I tried different ways of including newtonsoft in Program.cs, also i tried to make my model with [DataContract] excluding email field. If i remove builder.Services.AddMvc().AddNewtonsoftJson() then with email field validation is passing, but without it still failing. using System.Text.Json.Serialization not working too. What can i do?
CodePudding user response:
I fixed validation problem after making string nullable,
public string? Email { get; set; }