0
[HttpPost]
public IActionResult Post([FromBody]string value)
{
    string customMessage = "";
    int userId = GetUserIdFromUserInfo();
    //Reconstruct a useful object from the input string value. 
    dynamic missionNewInput = JsonConvert.DeserializeObject<dynamic>(value);
    MissionSynopsis newMission = new MissionSynopsis();

    try
    {   
        newMission.MissionSynopsisName = MissionNewInput.MissionSynopsisName.Value;
        newMission.CreatedById = userId;
        newMission.UpdatedById = userId;

        Database.MissionSynopses.Add(newMission);
        Database.SaveChanges();
    }
    catch (Exception exceptionObject)
    {
        if (exceptionObject.InnerException.Message
                  .Contains("MissionSynopsis_MissionSynopsisName_UniqueConstraint") == true) 
        {
            customMessage = "Unable to save ";


            object httpFailRequestResultMessage = new { message = customMessage };

            return BadRequest(httpFailRequestResultMessage);
        }
    }
}

System.NullReferenceException: 'Object reference not set to an instance of an object.'

pops up at the if statement of the catch part. How do I solve this?

croxy
  • 3,641
  • 8
  • 25
  • 42
  • Change it to `exceptionObject?.InnerException?.Message?.Contains` to protect against any of the properties being `null`. – mjwills Jun 13 '18 at 12:42
  • `InnerException` is `null`. – Llama Jun 13 '18 at 12:42
  • `InnerException` is most likely null, and therefore cannot access `Message`. – ThePerplexedOne Jun 13 '18 at 12:42
  • 4
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – croxy Jun 13 '18 at 12:45
  • I tried exceptionObject?.InnerException?.Message?.Contains. but it does not show any error and instead nothing happens, not even the custom message. how do i make InnerException not null? – Insidix Dark Jun 13 '18 at 13:04
  • You can't - it is `null` and there is no way to change that. Did you mean to use `exceptionObject?.Message` instead? – mjwills Jun 13 '18 at 13:24
  • Thanks exceptionObject?.Message worked !! However, when using the network monitoring tool for my web api, it says that it is successful 200 ok but there is no request payload even though there should be as i want to send a record to my sqldatabase – Insidix Dark Jun 13 '18 at 19:53

0 Answers0