Zam
Zam

Reputation: 3

Asp net core bad model in parameter at post action is not set to null

I have this problem I'm following the Api course on pluralsight and I've been trying to understand why when I pass an invalid Dto in a post request it doesn't get set to null. Here is my Dto

public class AuthorCreateDto
{
    public string Name { get; set; }

    public string LastName { get; set; }

    public int GenreId { get; set; }

    public int CountryId { get; set; }
}

and action

    [Route("")]
    [HttpPost]
    public ActionResult<AuthorDto> CreateAuthor([FromBody]AuthorCreateDto authorCreateDto)
    {
        if (authorCreateDto == null)
            return BadRequest();

        var author = Mapper.Map<Author>(authorCreateDto);

        if (TryValidateModel(author))
            return BadRequest();

        var newAuthor = _authorService.CreateAuthor(author);

        var newAuthorDto = Mapper.Map<AuthorDto>(newAuthor);

        return CreatedAtRoute("GetAuthor", new { id = newAuthor.Id }, newAuthorDto);
    }

so when I post an invalid json as

{ "epa": 2, "wdawd": "awdawd" }

authorCreateDto does not get set to null while on the course it does. Idk whats going on thank you

Upvotes: 0

Views: 525

Answers (1)

Edward
Edward

Reputation: 30036

For Asp.Net Core, its built-in serializer is Newtonsoft.Json and for FromBody, it will use JsonInputFormatter to bind the request body to model.

By default, SerializerSettings.MissingMemberHandling is Ignore which return default value for the properties which is missing in the request body.

If you prefer null for authorCreateDto, you could configure it with Error by

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddJsonOptions(options => {
                    options.SerializerSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Error;
                });
    }

Upvotes: 1

Related Questions