0

I'm new with ASP.NET Web API's and I'm trying to write an API method that will send emails.

This is my sendEmail controller:

[Route("sendemail")]
[HttpPost]
public bool SendEmail(EmailObj email)
{
    var To = email.sendTo;
    var Subject = email.subject;
    var Message = email.message;
    ...
}

However, whenever I test it using postman, the object sent is null. This is how my json object is built in postman:

{
    "subject": "Test Message",
    "message": "this is a test",
    "sendTo": "sam@test.com"
}

I make sure that the type is marked as JSON on postman and tried formatting it in different ways, but it doesn't seem to work. The API recieves the email object but is always null.

Here's a screenshot of my postman in case I'm missing something.

Any help is appreciated.

Edit: Already tried adding "[FromBody]" and adding "email: {}" to the json but it doesn't work.

3 Answers3

0

You can do 2 things:

public bool SendEmail([FromBody]EmailObj email)

Or change the body of the json object to:

{
    "email": {
        "subject": "Test Message",
        "message": "this is a test",
        "sendTo": "sam@test.com"
    }
}
Figurys
  • 46
  • 5
0

I found what was the mistake, I was declaring my email object as 'Serializable' and that was preventing the json object to get any value.

0

You can compare your controller with below code and you can click this link and see the output.

[RoutePrefix("api/test")]
public class TestController : ApiController
{

   [Route("sendemail")]
   [HttpPost]
   public bool SendEmail(EmailObj email)
   {
       if(email !=null)
       {
           return true;
       }
       return false;
   }

}

public class EmailObj
{
    public string sendTo { get; set; }
    public string subject { get; set; }
    public string message { get; set; }
}

This is my postman image that how I have called the post api.

This is my WebApi.config file image.