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?