0

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

4
  • 1
    What is the argument value of the authorCreateDto parameter than? Commented Feb 2, 2019 at 5:01
  • 1
    How are you posting this object? Commented Feb 2, 2019 at 13:08
  • Are you using the same version of ASP.NET Core as the course? Commented Feb 2, 2019 at 13:47
  • No, I'm using the 2.1 sdk Commented Feb 2, 2019 at 13:49

1 Answer 1

1

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;
                });
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.