0

I am making an api with asp.net core. Made an send email endpoint which also is accepting file for attachments. Problem is if the frontend is not sending a file the they get a badrequest error "System.NullReferenceException: Object reference not set to an instance of an object. at CounterCoreApi.Controllers.MailController.PostMail(Message message)"

Here is my controller

[HttpPost]
        [Consumes("multipart/form-data")]
        public async Task<IActionResult> PostMail([FromForm] Message message)
        {
           if (message.File != null || message.File.Length > 0)
                {
                   //I add attachment etc.
                 }
        }

And this is my message model

 public class Message
    {
        public string Subject { get; set; }
        public string MessageBody { get; set; }
        public IFormFile File { get; set; }
    }

If they post a file then there is no errors. I even tried adding ? after iformfile still same. Any suggesstions?

  • 1
    If `message.File` is null, it's going to go into the 2nd condition on your if statement, right? and then it's going to access the .Length property on a null object, resulting in a NullReferenceException. Perhaps you should change that from an `||` to an `&&`. – mason May 27 '20 at 14:07
  • The fact that you get a `NullReferenceException` itself shows that your `File` property **is** nullable, as it is **because** you try to read its `.Length` property when it's `null` that you get this exception. Maybe reading [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) could help you – Rafalon May 27 '20 at 14:11
  • Omg that was it. Thanks a lot – emrah sümer May 27 '20 at 14:14

0 Answers0